npm switches mirrors

npm 切换国内镜像

nrm use taobao

📝 笔记总结

推荐使用 nrm,命令简单,切换方便。

1
2
3
4
5
6
7
8
9
10
11
# 1. 全局安装 nrm
npm install -g nrm

# 2. 查看所有可用的源(带 * 的是当前源)
nrm ls

# 3. 切换到淘宝镜像
nrm use taobao

# 4. 验证是否设置成功
npm config get registry

📖 内容来源

🎯 最新稳定镜像地址

在国内使用 npm,切换镜像源几乎是必做的优化。核心操作很简单,但注意务必使用最新的地址。

淘宝 NPM 镜像(强烈推荐)

1
https://registry.npmmirror.com/

特别提醒:淘宝 NPM 官方源地址已于 2024 年迁移至 npmmirror.com,旧的 npm.taobao.org 域名已废弃,请勿继续使用。

其他备选国内镜像源还有:

  • 腾讯云:https://mirrors.cloud.tencent.com/npm/
  • 华为云:https://mirrors.huaweicloud.com/repository/npm/
  • 阿里云:https://npm.aliyun.com

🔧 切换方法

临时使用(仅对当前命令生效)

安装单个包时,直接通过 --registry 参数指定:

1
npm install [package-name] --registry=https://registry.npmmirror.com

这种方法快速、安全,适合临时下载某个包。

永久修改(全局生效)

通过 npm config set 命令修改全局配置,这是最常用的方法:

1
2
3
4
5
# 设置淘宝镜像为默认源
npm config set registry https://registry.npmmirror.com

# 验证是否设置成功
npm config get registry

执行后,所有 npm install 都将使用国内镜像。

高级管理:nrm

如果经常需要在多个镜像源(如官方、淘宝、公司私有源)间切换,推荐使用 nrm 工具来管理:

1
2
3
4
5
6
7
8
9
10
11
12
# 1. 全局安装 nrm
npm install -g nrm

# 2. 查看所有可用的源(带 * 的是当前源)
nrm ls

# 3. 切换到淘宝镜像
nrm use taobao

# 4. 验证是否设置成功
npm config get registry

这样,只需要输入 nrm use taobaonrm use npm 就能一键切换,无需记忆或输入长串地址。

可以随时切换回来,或者换成其他。

💡 备选方案:cnpm

除了修改 npm 源,也可以直接安装 cnpm 工具,自动使用淘宝镜像,与 npm 命令基本一致:

1
2
npm install -g cnpm --registry=https://registry.npmmirror.com
# 之后使用 cnpm 代替 npm,如:cnpm install

按需选择最适合的方法就好。设置完后可以运行 npm config get registry 确认一下,新地址是 https://registry.npmmirror.com/ 就说明成功了。