一句话:三件套包管理器的核心就三件事——装包、清缓存、改目录和镜像;冲突时用 legacy-peer-deps 或 shamefully-hoist 兜底。
写在前面
前端项目里 npm、yarn、pnpm 常混用;换机器后全局包装了却「命令找不到」,多半是 prefix / 全局目录没进 PATH。本篇按工具分块,并补充镜像、卸载 Node、依赖冲突等运维向命令。
核心内容
npm
| 命令 | 说明 |
|---|---|
npm cache clean --force |
强制清缓存 |
npm cache verify |
校验缓存完整性 |
npm config list |
查看当前配置 |
npm install --legacy-peer-deps |
忽略 peer 依赖冲突安装 |
npm uninstall pkg --save |
卸载并更新 dependencies |
npm uninstall pkg --save-dev |
卸载并更新 devDependencies |
自定义缓存与全局目录(Windows 示例)
bash
npm config set cache "D:\env\npm\cache"
npm config set prefix "D:\env\npm\global"
改 prefix 后需把 D:\env\npm\global 加入系统 Path,并可选设置 NODE_PATH 指向同一目录。
镜像源
bash
npm config set registry https://registry.npmmirror.com # 淘宝镜像
npm config set registry https://registry.npmjs.org # 官方源
依赖冲突
出现 ERESOLVE unable to resolve dependency tree 时:
bash
npm install --legacy-peer-deps
新版 npm 对 peerDependencies 更严格;--force 粗暴覆盖,优先用 --legacy-peer-deps。
yarn
| 命令 | 说明 |
|---|---|
yarn cache clean |
清缓存 |
yarn config list |
查看配置 |
bash
yarn config set cache-folder "D:\env\yarn\cache"
yarn config set global-folder "D:\env\yarn\global"
镜像:
bash
yarn config set registry https://registry.npmmirror.com
yarn config set registry https://registry.npmjs.org
安装 yarn:npm install -g yarn 后 Windows 若命令无效,可从 Yarn 官网 下载安装包,确保 global bin 在 Path 中。
pnpm
bash
npm install -g pnpm
pnpm -v
若改过 npm 的 global prefix,pnpm 可能找不到;把 global 目录加入 Path。
扁平 node_modules(兼容老项目)
bash
pnpm install --shamefully-hoist
或在项目根 .npmrc 写 shamefully-hoist=true,行为接近 npm/yarn 的 hoist。
镜像:
bash
pnpm config set registry https://registry.npmmirror.com
pnpm config set registry https://registry.npmjs.org
必备工具:rimraf
跨平台删除 node_modules(Windows 路径过长时尤其有用):
bash
npm install rimraf -g
rimraf node_modules
彻底卸载 Node.js(Windows checklist)
- 控制面板卸载 Node.js;
- 结束残留 node 进程;
- 删除(若存在):
C:\Program Files\nodejsC:\Program Files (x86)\nodejs%AppData%\npm与%AppData%\npm-cache
- 检查 Path 是否仍引用旧 node 路径;
where node确认无残留;- 重启终端。
踩坑
- 改 prefix 后全局命令找不到:Path 加
%prefix%或具体 global 目录,管理员 CMD 再试。 - npm / yarn / pnpm 锁文件勿混用:同一项目选定一种工具,提交对应 lockfile。
- pnpm 严格依赖:子包找不到模块时先试
shamefully-hoist,再查是否应声明为 direct dependency。 --legacy-peer-deps是权宜之计:长期应升级冲突包或对齐 peer 版本。
小结
- 三工具都支持:
config set cache/ 镜像registry/ 清缓存。 - Windows 迁目录:prefix + Path + NODE_PATH 三件套。
- 删 node_modules 用 rimraf;装包冲突用 --legacy-peer-deps 或 pnpm --shamefully-hoist。


全部评论(0)