nrm 安装与使用指南
什么是 nrm
nrm(NPM Registry Manager)是一个 npm 镜像源管理工具,可以快速切换不同的 npm registry 地址。在国内开发环境中,经常需要在 npm 官方源和淘宝镜像源之间切换,nrm 让这个过程变得非常简单。
安装
bash
npm install -g nrm验证安装:
bash
nrm --version常用命令
查看可用的镜像源
bash
nrm ls输出示例:
npm ---------- https://registry.npmjs.org/
yarn --------- https://registry.yarnpkg.com/
tencent ------ https://mirrors.tencent.com/npm/
cnpm --------- https://r.cnpmjs.org/
taobao ------- https://registry.npmmirror.com/
npmMirror ---- https://skimdb.npmjs.com/registry/
huawei ------- https://repo.huaweicloud.com/repository/npm/
* tudou -------- http://nexus.e-tudou.com/repository/tudou-npm-public/带 * 号的是当前正在使用的源。
切换镜像源
bash
# 切换到淘宝镜像(国内推荐)
nrm use taobao
# 切换回 npm 官方源
nrm use npm
# 切换到腾讯镜像
nrm use tencent测试各源的响应速度
bash
# 测试所有源的速度
nrm test
# 测试指定源
nrm test taobao输出示例:
npm ---------- 823ms
yarn --------- 757ms
tencent ------ 72ms
cnpm --------- 219ms
* taobao ------- 54ms
npmMirror ---- 1603ms
huawei ------- 89ms根据测试结果选择最快的源。
添加自定义源
公司内部可能有私有 npm 仓库(如 Nexus),可以添加自定义源:
bash
nrm add tudou http://nexus.e-tudou.com/repository/tudou-npm-public/删除自定义源
bash
nrm del tudou查看当前使用的源
bash
nrm current常用镜像源说明
| 源名称 | 地址 | 说明 |
|---|---|---|
| npm | https://registry.npmjs.org/ | 官方源,国外服务器 |
| taobao | https://registry.npmmirror.com/ | 淘宝镜像,国内最常用 |
| tencent | https://mirrors.tencent.com/npm/ | 腾讯云镜像 |
| huawei | https://repo.huaweicloud.com/repository/npm/ | 华为云镜像 |
| cnpm | https://r.cnpmjs.org/ | cnpm 镜像 |
实际使用场景
日常开发:使用淘宝镜像
bash
nrm use taobao
npm install # 从淘宝镜像下载,速度快发布 npm 包:切回官方源
bash
nrm use npm
npm publish # 发布必须使用官方源发布 npm 包时必须切换到官方源,使用镜像源发布会失败。
公司项目:使用私有源
bash
nrm use tudou
npm install # 从公司私有仓库下载不用 nrm 的替代方式
如果不想安装 nrm,也可以直接用 npm 命令管理源:
bash
# 查看当前源
npm config get registry
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com/
# 恢复官方源
npm config set registry https://registry.npmjs.org/
# 单次安装时指定源(不修改全局配置)
npm install --registry https://registry.npmmirror.com/nrm 的优势在于:
- 不需要记住各个源的完整 URL
- 切换更快捷(
nrm use taobaovs 手动输入 URL) - 可以测速帮你选择最快的源
- 方便管理多个自定义源
常见问题
Q: nrm 和 cnpm 有什么区别?
- nrm 只是切换 npm 的 registry 地址,使用的还是 npm 命令
- cnpm 是一个独立的包管理客户端,命令是
cnpm install
推荐使用 nrm + npm 的方式,因为 cnpm 安装的 node_modules 目录结构和 npm 不同,可能导致某些项目出问题。
Q: pnpm / yarn 也能用 nrm 切换源吗?
nrm 切换的是 npm 的 registry 配置。pnpm 默认读取 npm 的配置,所以 nrm 切换后 pnpm 也会生效。yarn (v1) 有独立的 registry 配置,需要单独设置:
bash
yarn config set registry https://registry.npmmirror.com/Q: nrm ls 报错 open is not defined?
这是 nrm 的一个已知 bug(出现在 Node.js 17+ 版本),可以通过以下方式修复:
bash
# 找到 nrm 的安装位置
npm root -g
# 编辑 nrm 目录下的 cli.js 文件
# 将 const open = require('open') 替换为:
# const open = await import('open')或者直接安装修复版本:
bash
npm install -g nrm@latest