1. 使用国内镜像源
npm 默认的镜像源是 https://registry.npmjs.org/
,由于服务器在国外,下载速度较慢。可以通过切换到国内镜像源(如淘宝镜像)来加速。
1.1 临时切换镜像源
在安装包时,使用 --registry
参数指定镜像源:
| npm install express --registry=https://registry.npmmirror.com |
复制
1.2 永久切换镜像源
通过以下命令将 npm 的默认镜像源修改为淘宝镜像:
| npm config set registry https://registry.npmmirror.com |
复制
验证镜像源是否修改成功:
复制
2. 使用 nrm 管理镜像源
nrm
是一个 npm 镜像源管理工具,可以快速切换不同的镜像源。
2.1 安装 nrm
复制
2.2 查看可用镜像源
复制
输出示例:
| * npm ---- https: |
| yarn ---- https: |
| taobao -- https: |
| ... |
复制
2.3 切换镜像源
复制
2.4 测试镜像源速度
复制
3. 使用代理或 VPN
如果你所在的网络环境限制了 npm 的访问速度,可以尝试使用代理或 VPN 来加速。
3.1 设置代理
通过以下命令设置 HTTP 或 HTTPS 代理:
| npm config set proxy http://proxy.example.com:8080 |
| npm config set https-proxy http://proxy.example.com:8080 |
复制
3.2 取消代理
| npm config delete proxy |
| npm config delete https-proxy |
复制
4. 清理 npm 缓存
npm 会将下载的包缓存到本地,如果缓存文件损坏或过多,可能会导致安装速度变慢。可以通过以下命令清理缓存:
复制
5. 使用 cnpm 替代 npm
cnpm
是淘宝团队提供的 npm 镜像工具,专门用于加速 npm 包的安装。
5.1 安装 cnpm
| npm install -g cnpm --registry=https://registry.npmmirror.com |
复制
5.2 使用 cnpm
使用 cnpm
代替 npm
安装包:
复制
6. 优化 npm 安装的其他技巧
总结
通过切换国内镜像源、使用 nrm
管理镜像、设置代理或 VPN、清理缓存以及使用 cnpm
等方法,你可以显著提升 npm 的安装速度。这些技巧不仅适用于个人开发环境,也适用于团队协作和 CI/CD 环境,能够有效提高开发效率。
参考资料:
- npm 官方文档
- 淘宝 npm 镜像
- nrm GitHub 仓库