包管理器对比与镜像配置
npm / Yarn / pnpm 对比
| 维度 | npm(7+) | Yarn Classic | pnpm |
|---|---|---|---|
| 锁文件 | package-lock.json | yarn.lock | pnpm-lock.yaml |
| 磁盘 | 每项目完整 node_modules | 缓存 + 复制,中等 | 全局 store + 硬链接,通常最省 |
| 安装速度 | 较快 | 快 | 通常最快 |
| Monorepo | workspaces | workspaces | 路径隔离好,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 nrm → nrm 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 同类)
| 操作 | npm | Yarn | pnpm |
|---|---|---|---|
| 安装全部 | npm install | yarn | pnpm install |
| 添加依赖 | npm i 包 | yarn add 包 | pnpm add 包 |
| 开发依赖 | -D | -D | -D |
| 移除 | npm un 包 | yarn remove 包 | pnpm remove 包 |
| 运行脚本 | npm run xxx | yarn xxx | pnpm xxx 或 pnpm run xxx |
pnpm 清理全局存储:pnpm store prune。幽灵依赖问题可查 public-hoist-pattern、shamefully-hoist(以官方文档为准)。
小结
锁文件 + 统一包管理器 + 明确 Registry,是 可复现构建 的基础;镜像加速安装,发布走官方;企业可配合 私有 Registry(如 Verdaccio、Artifactory)。
