如何配置 .npmrc 使 scope 指向 Nexus group

解读

在国内企业级 CI/CD 与私有源治理场景中,Nexus Repository Manager 常被用作统一制品仓库,既缓存官方 npm 镜像,又托管公司内部 scope 包。面试时,面试官想确认候选人是否真正落地过“scope 级私有源隔离”方案,而不仅仅停留在 registry 层面。回答必须体现三点:

  1. 明确区分 @scope:registry 与 registry 两条指令;
  2. 给出 鉴权、SSL、缓存、锁文件一致性 的配套写法;
  3. 能解释为何用 Nexus group(聚合 npm-central、npm-hosted、npm-proxy)而非单一 hosted,以体现对 Nexus 路由策略的理解。

知识点

  • .npmrc 作用域优先级:项目级 > 用户级 > 全局级,CI 场景通常把 .npmrc 放在项目根并加密入库。
  • @scope:registry 语法:仅把指定 scope 的流量转发到私有源,其余包仍走官方或镜像源,避免“全量代理”带来的性能与合规风险。
  • Nexus group 仓库路径:group 本身不存包,只做路由;其 URL 必须以 /repository/npm-group/ 结尾,而非 /content/groups/ 旧版路径。
  • _authToken 与 always-auth:国内 Nexus 常关匿名读,需配置 _authToken(Base64 用户名:密码)或 //domain/:_authToken;always-auth=true 防止 401 重试。
  • strict-ssl 与 cafile:内网自签证书场景需 strict-ssl=false 或指定 cafile=./certs/nexus-ca.crt,否则 CI 报 UNABLE_TO_VERIFY_LEAF_SIGNATURE。
  • package-lock 一致性:若 Nexus 上游代理官方源,需保证 lockfileVersion 与 npm 版本一致,否则本地与 CI 解析树差异导致“幽灵依赖”。
  • 缓存与离线镜像:cache-min=86400 与 prefer-offline=true 可降低对 Nexus 的 QPS,防止大促期间 Nexus 因瞬时并发而 502。

答案

  1. 在项目根创建 .npmrc,内容如下:
@mycompany:registry=https://nexus.infra.cn/repository/npm-group/
//nexus.infra.cn/repository/npm-group/:_authToken="YWRtaW46YWRtaW4xMjM="
always-auth=true
strict-ssl=false
cafile=./certs/nexus-ca.crt
save-exact=true
package-lock=true
  1. 解释每一行:
  • @mycompany:registry 把以 @mycompany/ 开头的包全部路由到 Nexus group;
  • //domain/…:_authToken 采用 Base64 编码的“用户名:密码”,CI 中通过 echo -n 'user:pass' | base64 -w0 生成,避免明文;
  • always-auth=true 保证每次请求都带 Authorization,防止 Nexus 的 401 重定向;
  • strict-ssl=false 仅在内网自签场景使用,生产环境应换成 cafile 指向企业根证书;
  • save-exact & package-lock 确保版本锁定,实现“可复现安装”。
  1. 验证:
npm config list | grep mycompany
npm whoami --registry https://nexus.infra.cn/repository/npm-group/
npm install @mycompany/common@1.0.0 --verbose

若返回 200 且包体来自 Nexus,即配置成功。

拓展思考

  • 多 scope 多 group 场景:若公司存在 @fe、 @be 两个 scope,但分别指向不同的 Nexus group,可在 .npmrc 写多行 @fe:registry=…、 @be:registry=…,实现“scope 级租户隔离”,避免单 group 成为瓶颈。
  • CI 动态注入:在 GitLab-CI 中,用 before_script 把 NEXUS_AUTH 变量写入 .npmrc,并设置 mask: true,防止 token 泄露到日志。
  • npm v9 新策略:auth-type=legacy 已被废弃,若 Nexus 3.50+ 开启 Bearer Token,需改用 //domain/:_authToken=${NEXUS_BEARER} 并升级 npm 至 9.5+,否则报 401。
  • 性能调优:Nexus group 默认把官方源放在最末,若国内网络访问 registry.npmjs.org 慢,可在 Nexus 里把 npm-proxy 上游改为 https://registry.npmmirror.com,并在 .npmrc 加 fetch-retry-mintimeout=20000,降低超时失败率。