npmrc 配置文件
一、避坑指南(必看)
.npmrc有 4 个位置,优先级从高到低:- 项目级
./.npmrc(团队共享,必须 commit) - 用户级
~/.npmrc(个人配置,不能 commit) - 全局级
$PREFIX/etc/npmrc - 内置级(npm 自带)
面试高频:离当前目录最近的
.npmrc生效。项目级会覆盖用户级,这是为什么团队能强制统一 registry 而个人配置不冲突。- 项目级
敏感信息绝不入仓:
- ❌ 错误:把
_authToken=xxx写进项目级.npmrc并 push - ✅ 正确:项目级只放
registry/scope等公共配置,token 放用户级~/.npmrc或 CI 的 Secret
- ❌ 错误:把
不同包管理器读不同的 rc 文件:
工具 配置文件 是否兼容 .npmrcnpm .npmrc— yarn .yarnrc/.npmrc兼容部分 pnpm .npmrc完全兼容 bun .npmrc完全兼容 pnpm 之所以体验顺,是因为直接复用 npm 生态配置,零迁移成本。
原生模块必须配镜像(国内必踩的坑):
canvas/node-sqlite3/better-sqlite3/sharp/electron/node-sass都会从国外源拉预编译二进制,不配镜像 90% 会超时。
二、核心配置项
# === 基础 ===
registry=https://registry.npmmirror.com
# === 推荐开启 ===
# 锁版本号,避免 ^~ 的隐式升级
save-exact=true
# 强校验 Node 版本(与 package.json 的 engines 配合)
engine-strict=true
# 安装时跳过 audit(CI 加速)
audit=false
# === scope 私有 registry(企业内网常用)===
@my-org:registry=https://npm.internal.com
# 携带 token 走用户级 ~/.npmrc
//npm.internal.com/:_authToken=${NPM_TOKEN}
# === 原生模块镜像(按需保留)===
sass_binary_site=https://registry.npmmirror.com/-/binary/node-sass
sharp_libvips_binary_host=https://registry.npmmirror.com/-/binary/sharp-libvips
electron_mirror=https://registry.npmmirror.com/-/binary/electron/
electron_builder_binaries_mirror=https://registry.npmmirror.com/-/binary/electron-builder-binaries/
canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas
node_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3
better_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3
python_mirror=https://registry.npmmirror.com/-/binary/python/
命名规则:
{pkg-name}_binary_host_mirror={mirror}是通用模板,按需替换包名即可。
三、面试话术
「
.npmrc分四级,项目级最高。团队协作时,公共配置(registry、原生模块镜像)放项目级一起 commit,token 这种敏感信息走用户级或 CI Secret。pnpm 完美兼容.npmrc,所以公司统一包管理工具时基本零阻力。」
四、字段速查(字典式参考)
按字段名检索。
| 字段 | 作用 | 备注 |
|---|---|---|
registry | 包下载地址 | 项目级强约束 |
save-exact | npm i 时锁精确版本(不写 ^) | 推荐 true |
save-prefix | npm i 时前缀,默认 ^ | 配合 save-exact=false 生效 |
engine-strict | Node 版本不符直接报错 | 配合 engines 字段 |
audit | 是否进行安全审计 | CI 设 false 提速 |
fund | 是否显示赞助信息 | 设为 false 干净 |
package-lock | 是否生成 lock | false 可关闭(不推荐) |
@scope:registry | 私有 scope 走单独 registry | 配合 token 使用 |
cache | 缓存目录 | CI 可改到 ~/.npm |
prefix | 全局安装目录 | 默认 /usr/local |
{pkg}_binary_host_mirror | 原生模块二进制镜像 | 通用命名规则 |