编辑
2024-11-15
技术相关
00
请注意,本文编写于 159 天前,最后修改于 159 天前,其中某些信息可能已经过时。

目录

1. 直接使用 npm 配置国内源
2. 临时使用国内源
3. 使用 cnpm(推荐)
安装 cnpm:
使用 cnpm 安装依赖:
4. 使用 nrm 切换多个源(更灵活)
安装 nrm:
查看可用源列表:
切换到淘宝源:
测试速度:
切换回官方源:
5. 使用 Yarn 配置国内源
注意事项

切换到国内的 npm 源可以提高依赖安装的速度,特别是在国内网络环境下常使用 npmyarn 时。以下是切换 npm 源的常用方法:

image.png


1. 直接使用 npm 配置国内源

使用以下命令将 npm 的默认源切换为国内镜像(如淘宝镜像):

npm config set registry https://registry.npmmirror.com/

验证是否设置成功:

npm config get registry

输出应为:

https://registry.npmmirror.com/

2. 临时使用国内源

如果只想临时切换源安装一个包,可以在安装命令前添加 --registry 参数:

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

3. 使用 cnpm(推荐)

cnpm 是淘宝 NPM 镜像的命令行工具,安装后可以更方便地使用国内源。

安装 cnpm

npm install -g cnpm --registry=https://registry.npmmirror.com/

使用 cnpm 安装依赖:

cnpm install

cnpm 会自动使用淘宝源,无需额外配置。


4. 使用 nrm 切换多个源(更灵活)

nrm 是一个管理和切换 npm 源的工具,支持多源切换,非常方便。

安装 nrm

npm install -g nrm

查看可用源列表:

nrm ls

输出示例:

* npm -------- https://registry.npmjs.org/ yarn ------- https://registry.yarnpkg.com/ taobao ----- https://registry.npmmirror.com/

切换到淘宝源:

nrm use taobao

测试速度:

nrm test

切换回官方源:

nrm use npm

5. 使用 Yarn 配置国内源

如果使用的是 Yarn,可以通过以下命令切换到国内源:

yarn config set registry https://registry.npmmirror.com/

验证是否设置成功:

yarn config get registry

注意事项

  • 使用国内镜像时,请确保源是可信任的,比如淘宝镜像(https://registry.npmmirror.com/)。
  • 如果需要频繁切换,可以优先选择 nrm,管理和切换更方便。
  • 配置完成后,记得清理之前的缓存以避免冲突:
npm cache clean --force

本文作者:Kevin@灼华

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!