本文介绍如何通过npm快速安装Yarn和pnpm,并配置国内镜像源提升依赖下载速度,解决开发者在国内网络环境下安装Node.js包缓慢的问题。
1. 为什么选择Yarn和pnpm?
- Yarn:由Facebook开发的包管理工具,支持并行下载、缓存优化和版本锁定,提升安装效率。
- pnpm:采用硬链接技术,节省磁盘空间,加速安装速度,严格管理依赖树避免重复。
2. 通过npm全局安装Yarn和pnpm
2.1 安装Yarn
打开终端(Windows需管理员权限),执行以下命令:
npm install -g yarn
验证安装:
yarn --version
2.2 安装pnpm
同样使用npm全局安装:
npm install -g pnpm
验证安装:
pnpm --version
3. 配置国内镜像加速
3.1 配置Yarn国内镜像
设置默认仓库镜像(以淘宝源为例):
yarn config set registry https://registry.npmmirror.com
3.2 配置pnpm国内镜像
设置pnpm仓库镜像:
pnpm config set registry https://registry.npmmirror.com
4. 验证镜像配置
-
Yarn:
yarn config get registry # 应输出 https://registry.npmmirror.com -
pnpm:
pnpm config get registry # 应输出 https://registry.npmmirror.com
5. 其他国内镜像源(备用)
若淘宝源不稳定,可切换至以下镜像:
-
腾讯云:
yarn config set registry https://mirrors.cloud.tencent.com/npm/ pnpm config set registry https://mirrors.cloud.tencent.com/npm/ -
华为云:
yarn config set registry https://mirrors.huaweicloud.com/repository/npm/ pnpm config set registry https://mirrors.huaweicloud.com/repository/npm/
6. 常见问题解决
6.1 安装权限问题
- Linux/macOS:在命令前加
sudo:sudo npm install -g yarn - Windows:以管理员身份运行终端。
6.2 恢复默认配置
# Yarn
yarn config set registry https://registry.yarnpkg.com
# pnpm
pnpm config set registry https://registry.npmjs.org
&spm=1001.2101.3001.5002&articleId=146047233&d=1&t=3&u=102ae64e660341cf9ca5204147d6b4ce)
7111

被折叠的 条评论
为什么被折叠?



