npm 加速

npm 镜像加速

把 npm 的 registry 指向本站,元数据与 tarball 都会通过本站代理下载。

● 兼容 npm / pnpm / yarn ● 支持 scoped 包 ● tarball 地址自动改写

registry 地址

推荐用脚本
registry(结尾的斜杠不要省略)
https://gh-proxy.cn/npm/

脚本会写 ~/.npmrc,同时处理 yarn 的两种配置格式,并保留已有的 token 等配置:

默认:当前用户
curl -fsSL https://gh-proxy.cn/scripts/npm.sh | sh

先预览会改什么

--dry-run
sh npm.sh --dry-run

全局配置 / 还原 / 二进制镜像

常用参数
sudo sh npm.sh --global        # 写入全局 npmrc
sh npm.sh --restore            # 还原到执行前
sh npm.sh --dist               # 同时指向 electron 等二进制镜像

写入 ~/.npmrc(pnpm 也读这个文件):

.npmrc
registry=https://gh-proxy.cn/npm/

或者用命令行写入

npm config
npm config set registry https://gh-proxy.cn/npm/
npm config get registry

yarn 2+ / yarn 1.x

yarn
# yarn 2+:写入 .yarnrc.yml
echo 'npmRegistryServer: "https://gh-proxy.cn/npm/"' >> ~/.yarnrc.yml
# yarn 1.x:写入 .yarnrc
yarn config set registry https://gh-proxy.cn/npm/

不改配置,只在本次安装时使用镜像:

单次安装
npm install --registry https://gh-proxy.cn/npm/ vue
pnpm add --registry https://gh-proxy.cn/npm/ vue

接口对照

GET /npm/<包名>
包元数据(版本、依赖)
GET /npm/@scope%2f<包名>
scoped 包元数据
GET /npm/<包名>/-/<文件>.tgz
tarball 下载
GET /npm/-/v1/search
搜索接口

元数据里 dist.tarball 指向上游 registry 的地址会被改写成本站地址, 这样 npm ci、pnpm、yarn 的缓存都会走镜像。

自检

shell
curl -s https://gh-proxy.cn/npm/-/ping
npm config get registry
npm view vue version
npm pack vue --dry-run
← 返回软件源加速