外观
npm / yarn / pnpm 走代理与切换镜像源加速安装
npm install 卡半天下不动,通常两条路能解决:换镜像源(国内 CDN,最常用)或走代理。两者可单用也可组合。
一、切换镜像源(最推荐,最简单)
国内镜像把 npm 官方仓库整体缓存到国内 CDN,速度飞快。
bash
# 设置为 npmmirror(原淘宝镜像)
npm config set registry https://registry.npmmirror.com
# 查看当前源
npm config get registry
# 改回官方源
npm config set registry https://registry.npmjs.org临时用一次、不改全局:
bash
npm install --registry=https://registry.npmmirror.com用 nrm 管理多个源
频繁切换的话装 nrm:npm i -g nrm,然后 nrm use taobao / nrm use npm 一键切换。
二、yarn / pnpm 换源
bash
# yarn (classic v1)
yarn config set registry https://registry.npmmirror.com
# yarn berry (v2+),在项目 .yarnrc.yml
# npmRegistryServer: "https://registry.npmmirror.com"
# pnpm
pnpm config set registry https://registry.npmmirror.com三、给 npm 配置代理
有些包(尤其带二进制、需从 GitHub 下载的)不走 registry,换源无效,得走代理:
bash
npm config set proxy http://127.0.0.1:7890
npm config set https-proxy http://127.0.0.1:7890
# 取消
npm config delete proxy
npm config delete https-proxy四、二进制依赖单独换源
像 node-sass、electron、puppeteer、sharp 这些会额外下载二进制,常卡在 GitHub。用环境变量指向国内镜像:
bash
# 写入 ~/.npmrc(或项目 .npmrc)
electron_mirror=https://npmmirror.com/mirrors/electron/
sass_binary_site=https://npmmirror.com/mirrors/node-sass
puppeteer_download_host=https://npmmirror.com/mirrors
sharp_binary_host=https://npmmirror.com/mirrors/sharp或安装时临时指定:
bash
ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ npm install electronWindows PowerShell:
powershell
$env:ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/"; npm install electron五、镜像源 vs 代理,怎么选
| 场景 | 首选 |
|---|---|
| 普通包 install 慢 | 换镜像源(方法一) |
| electron/puppeteer 等二进制卡住 | 二进制镜像(方法四) |
| 私有源 / 需要科学上网的包 | 代理(方法三) |
| 公司内网私有 registry | 别全局换源,用 .npmrc 按 scope 配置 |
按 scope 指定源(公司私有包 + 公共包混用):
text
# .npmrc
@mycompany:registry=https://npm.mycompany.com
registry=https://registry.npmmirror.com小结
- 90% 的慢换成
registry.npmmirror.com就好了。 - electron / puppeteer 这类卡二进制的,单独配镜像环境变量。
- 实在需要访问 GitHub 上的资源,再叠加 代理。
本文仅供技术学习与研究,请遵守所在国家/地区法律法规。