Published on
- 3 min read
📌 推荐文章
Cursor Rules - 国内npm源配置指南
基本规则
- 优先使用国内镜像源提高下载速度
- 提供多种配置方法供选择
- 包含常用包管理器的配置
npm 配置国内源
方法一:临时使用
# 使用淘宝镜像
npm install --registry https://registry.npmmirror.com
# 使用腾讯镜像
npm install --registry https://mirrors.cloud.tencent.com/npm/
方法二:全局配置
# 设置淘宝镜像为默认源
npm config set registry https://registry.npmmirror.com
# 验证配置
npm config get registry
# 恢复官方源
npm config set registry https://registry.npmjs.org/
方法三:使用 .npmrc 文件
在项目根目录创建 .npmrc
文件:
registry=https://registry.npmmirror.com
yarn 配置国内源
# 设置淘宝镜像
yarn config set registry https://registry.npmmirror.com
# 验证配置
yarn config get registry
# 恢复官方源
yarn config set registry https://registry.yarnpkg.com
pnpm 配置国内源
# 设置淘宝镜像
pnpm config set registry https://registry.npmmirror.com
# 验证配置
pnpm config get registry
# 恢复官方源
pnpm config set registry https://registry.npmjs.org/
推荐的国内镜像源
镜像源 | 地址 | 特点 |
---|---|---|
淘宝镜像 | https://registry.npmmirror.com | 最常用,更新及时 |
腾讯镜像 | https://mirrors.cloud.tencent.com/npm/ | 稳定可靠 |
华为镜像 | https://mirrors.huaweicloud.com/repository/npm/ | 企业级稳定 |
中科大镜像 | https://npmreg.proxy.ustclug.org/ | 学术网络友好 |
使用 nrm 管理多个源
# 安装 nrm
npm install -g nrm
# 查看可用源
nrm ls
# 切换到淘宝源
nrm use taobao
# 添加自定义源
nrm add custom https://registry.npmmirror.com
# 测试源速度
nrm test
项目级配置建议
在 package.json 中添加 npm scripts
{
"scripts": {
"install:taobao": "npm install --registry https://registry.npmmirror.com",
"install:tencent": "npm install --registry https://mirrors.cloud.tencent.com/npm/"
}
}
团队协作配置
在项目根目录创建 .npmrc
文件,确保团队使用相同的镜像源:
registry=https://registry.npmmirror.com
disturl=https://npmmirror.com/mirrors/node/
sass_binary_site=https://npmmirror.com/mirrors/node-sass/
phantomjs_cdnurl=https://npmmirror.com/mirrors/phantomjs/
electron_mirror=https://npmmirror.com/mirrors/electron/
常见问题解决
1. 某些包下载失败
# 临时切换回官方源
npm install package-name --registry https://registry.npmjs.org/
2. 私有包配置
# 为特定scope配置不同的registry
npm config set @company:registry https://npm.company.com
3. 清除缓存
# 清除npm缓存
npm cache clean --force
# 清除yarn缓存
yarn cache clean
# 清除pnpm缓存
pnpm store prune
自动化脚本
创建一个快速配置脚本 setup-npm-china.sh
:
#!/bin/bash
echo "配置npm国内镜像源..."
npm config set registry https://registry.npmmirror.com
npm config set disturl https://npmmirror.com/mirrors/node/
npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
echo "配置完成!当前registry: $(npm config get registry)"
验证配置
# 检查当前配置
npm config list
# 测试安装速度
time npm install lodash
# 查看包信息
npm info lodash
注意事项:
- 定期检查镜像源的可用性
- 某些企业内网可能需要特殊配置
- 发布包时记得切换回官方源