要变更 npm 的国内镜像源(registry),可以使用以下几种方法:
方法 1:临时使用国内镜像(单次生效)
在安装包时,直接指定镜像源:
bash
npm install --registry=https://registry.npmmirror.com
(适用于偶尔使用国内源的情况)
方法 2:永久切换 npm 默认源
2.1 使用 npm config 命令
bash
npm config set registry https://registry.npmmirror.com
验证是否修改成功:
bash
npm config get registry
应该返回:
text
https://registry.npmmirror.com
2.2 直接修改 npm 配置文件(~/.npmrc)
bash
echo "registry=https://registry.npmmirror.com" >> ~/.npmrc
(适用于 Linux/macOS,Windows 可手动编辑 C:\Users\<用户名>.npmrc)
方法 3:使用 nrm(npm 源管理器)
安装 nrm:
bash
npm install -g nrm
查看可用源列表:
bash
nrm ls
切换国内源(如淘宝源):
bash
nrm use taobao
测试源速度:
bash
nrm test taobao
国内常用 npm 镜像源
镜像源 地址
淘宝源 https://registry.npmmirror.com
腾讯云源 https://mirrors.cloud.tencent.com/npm/
华为云源 https://repo.huaweicloud.com/repository/npm/
cnpmjs https://r.cnpmjs.org/
恢复默认 npm 源
bash
npm config set registry https://registry.npmjs.org
注意事项
淘宝源(npmmirror.com) 是官方推荐的国内镜像,同步频率高(10分钟一次)。
如果使用 cnpm(淘宝提供的 npm 客户端),安装方式不同:
bash
npm install -g cnpm --registry=https://registry.npmmirror.com
切换源后,部分私有包可能需要额外配置认证(如企业内网 npm 仓库)。
总结
推荐长期使用:npm config set registry https://registry.npmmirror.com
临时使用:npm install --registry=xxx
多源切换:nrm 工具更方便
切换后,npm 下载速度会显著提升! 🚀