全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-25 8 分钟 ✍️ juanwangdev

NPM镜像源与私有仓库配置

镜像源解决下载速度问题,私有仓库保护内部包,scope绑定实现混合源路由。

镜像源切换

查看与设置

Bash
# 查看当前源
npm config get registry

# 切换到淘宝镜像
npm config set registry https://registry.npmmirror.com

# 切换回官方源
npm config set registry https://registry.npmjs.org

nrm管理源

Bash
npm install -g nrm

# 列出可用源
nrm ls

# 切换源
nrm use taobao

# 测试速度
nrm test

# 添加自定义源
nrm add company https://npm.company.com

项目级配置

在项目根目录创建.npmrc

ini
registry=https://registry.npmmirror.com

项目级.npmrc优先级高于全局配置,适合团队统一镜像源。

企业私有仓库

常见方案

方案特点
Verdaccio轻量级,零配置启动
Nexus功能全面,支持多语言包管理
Artifactory企业级,权限管理强
GitHub Packages与GitHub集成

Verdaccio快速搭建

Bash
# 安装
npm install -g verdaccio

# 启动(默认端口4873)
verdaccio

# 添加用户
npm adduser --registry http://localhost:4873

# 发布到私有仓库
npm publish --registry http://localhost:4873

Verdaccio配置

YAML
# config.yaml
storage: ./storage
uplinks:
  npmjs:
    url: https://registry.npmjs.org
packages:
  '@myorg/*':
    access: $authenticated
    publish: $authenticated
    proxy: npmjs
  '**':
    access: $all
    proxy: npmjs

Verdaccio的proxy配置实现缓存代理:私有包从本地获取,公共包从npmjs代理并缓存。

scope绑定registry

按scope路由

将特定scope的包路由到私有仓库,其他包走默认源:

ini
# .npmrc
registry=https://registry.npmmirror.com
@myorg:registry=https://npm.company.com

效果:

  • @myorg/utils → 从私有仓库安装
  • lodash → 从淘宝镜像安装

发布到私有仓库

ini
# .npmrc
@myorg:registry=https://npm.company.com
//npm.company.com/:_authToken=${NPM_TOKEN}
Bash
npm publish

@myorg包自动发布到绑定的registry,无需手动指定--registry。

认证配置

ini
# .npmrc
//npm.company.com/:_authToken=npm_xxxx
//npm.company.com/:always-auth=true

scope绑定registry是企业级标准做法,无需每次手动指定--registry。认证token不要提交到Git,使用环境变量${NPM_TOKEN}替代。

要点总结

  • nrm管理多个镜像源,支持切换和测速
  • 项目级.npmrc可覆盖全局registry配置
  • Verdaccio是轻量私有仓库方案,支持代理缓存
  • @scope:registry将特定命名空间路由到私有仓库
  • 认证token用环境变量注入,避免硬编码到.npmrc
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 scoped包与权限标签管理
下一篇 → package-lock.json深入与冲突处理
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码