在 Mac 上找出并删除旧的 node_modules,又不弄坏项目

怎么按体积列出所有 node_modules,删之前怎么确认项目能重新安装,以及怎么清理 npm、pnpm 和 Yarn 的缓存。

node_modules 完全由 lockfile 决定,理论上随时可以删掉重装。实际上会出三种岔子:lockfile 从没提交过、有人直接改了里面的包、或者源上已经下不到你需要的版本。

按体积列出来

find ~/dev -name node_modules -type d -prune -exec du -sh {} + | sort -h

把 ~/dev 换成你放项目的位置。-prune 让 find 不再钻进嵌套的 node_modules。

删之前先检查

cd path/to/project
git status --short            # 有没有未提交的改动
git ls-files --error-unmatch package-lock.json   # lockfile 有没有被跟踪
git status --short --ignored node_modules | head  # 有没有意料之外的东西

删除与还原

rm -rf node_modules
npm ci        # 或:pnpm install --frozen-lockfile / yarn install --immutable

它们背后的缓存

npm cache verify            # 校验并压缩 ~/.npm/_cacache
npm cache clean --force     # 整个清掉
pnpm store prune            # 删除没有项目引用的包
yarn cache clean

清理 pnpm 请用 pnpm store prune,不要直接删 store 目录:store 里混着仍被项目链接的包和已经没人引用的包,只有 pnpm 自己分得清。

Siftaway 怎么处理

「项目产物」页会在你的各个仓库里找出 node_modules,并逐个仓库显示分支、未提交与未推送的改动、stash,以及 lockfile 是否完整。没通过这些检查的仓库不能勾选。勾选的目录移入废纸篓。