Skip to content

包管理器对比与镜像配置

npm / Yarn / pnpm 对比

维度npm(7+)Yarn Classicpnpm
锁文件package-lock.jsonyarn.lockpnpm-lock.yaml
磁盘每项目完整 node_modules缓存 + 复制,中等全局 store + 硬链接,通常最省
安装速度较快通常最快
Monorepoworkspacesworkspaces路径隔离好,Monorepo 常用
兼容性基准个别老包解析差异个别「幽灵依赖」需 hoist 配置

选型: 新项目可考虑 pnpm;存量项目 npm + lock 即可;统一一种 比工具更重要。


Registry 与镜像

国内常用镜像:https://registry.npmmirror.com

bash
npm config get registry
npm config set registry https://registry.npmmirror.com
npm config set registry https://registry.npmjs.org/   # 官方
npm install 包名 --registry=https://registry.npmmirror.com   # 单次临时

发布到 npm 官网前须切回官方源,避免误发到镜像。

nrm(可选):npm i -g nrmnrm ls / nrm use taobao / nrm test / nrm use npm


npm 配置优先级

命令行 > 项目 .npmrc > 用户 ~/.npmrc > 全局 > 默认。

bash
npm config list
npm config set key value [--global]
npm config delete key [--global]

代理(内网)

bash
npm config set proxy http://127.0.0.1:端口 --global
npm config set https-proxy http://127.0.0.1:端口 --global
npm config set no-proxy "localhost,127.0.0.1,*.公司域" --global

缓存

bash
npm cache verify          # 优先
npm cache clean --force   # 激进清空

Yarn / pnpm 命令对照(与 npm 同类)

操作npmYarnpnpm
安装全部npm installyarnpnpm install
添加依赖npm i 包yarn add 包pnpm add 包
开发依赖-D-D-D
移除npm un 包yarn remove 包pnpm remove 包
运行脚本npm run xxxyarn xxxpnpm xxxpnpm run xxx

pnpm 清理全局存储:pnpm store prune。幽灵依赖问题可查 public-hoist-patternshamefully-hoist(以官方文档为准)。


小结

锁文件 + 统一包管理器 + 明确 Registry,是 可复现构建 的基础;镜像加速安装,发布走官方;企业可配合 私有 Registry(如 Verdaccio、Artifactory)。