Skip to content

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-sasselectronpuppeteersharp 这些会额外下载二进制,常卡在 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 electron

Windows 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 上的资源,再叠加 代理

本文仅供技术学习与研究,请遵守所在国家/地区法律法规。

本站为技术学习交流站点,与 GitHub, Inc. 无任何隶属或官方关系。所有内容仅供技术研究与学习,请遵守所在国家/地区的法律法规。