Skip to main content

npmrc 配置文件

一、避坑指南(必看)

  1. .npmrc 有 4 个位置,优先级从高到低

    • 项目级 ./.npmrc(团队共享,必须 commit
    • 用户级 ~/.npmrc(个人配置,不能 commit
    • 全局级 $PREFIX/etc/npmrc
    • 内置级(npm 自带)

    面试高频:离当前目录最近的 .npmrc 生效。项目级会覆盖用户级,这是为什么团队能强制统一 registry 而个人配置不冲突。

  2. 敏感信息绝不入仓

    • ❌ 错误:把 _authToken=xxx 写进项目级 .npmrc 并 push
    • ✅ 正确:项目级只放 registry / scope 等公共配置,token 放用户级 ~/.npmrc 或 CI 的 Secret
  3. 不同包管理器读不同的 rc 文件

    工具配置文件是否兼容 .npmrc
    npm.npmrc
    yarn.yarnrc / .npmrc兼容部分
    pnpm.npmrc完全兼容
    bun.npmrc完全兼容

    pnpm 之所以体验顺,是因为直接复用 npm 生态配置,零迁移成本。

  4. 原生模块必须配镜像(国内必踩的坑): 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-exactnpm i 时锁精确版本(不写 ^推荐 true
save-prefixnpm i 时前缀,默认 ^配合 save-exact=false 生效
engine-strictNode 版本不符直接报错配合 engines 字段
audit是否进行安全审计CI 设 false 提速
fund是否显示赞助信息设为 false 干净
package-lock是否生成 lockfalse 可关闭(不推荐)
@scope:registry私有 scope 走单独 registry配合 token 使用
cache缓存目录CI 可改到 ~/.npm
prefix全局安装目录默认 /usr/local
{pkg}_binary_host_mirror原生模块二进制镜像通用命名规则

五、相关文档