不清理 'node_modules'(提交 1GB 依赖到 Git)
提交 1GB 的 node_modules
到 Git 仓库,是让团队协作崩溃的经典操作。依赖目录的膨胀速度远超想象,而将其纳入版本控制,不仅浪费存储空间,还会让每次 git clone
变成一场漫长的等待。
为什么 node_modules
不该进 Git
node_modules
是 npm
或 yarn
安装依赖时自动生成的目录,通常包含以下问题:
- 体积爆炸:一个中型项目的
node_modules
轻松突破 200MB,带devDependencies
可能超过 1GB。 - 平台特异性:某些依赖(如
node-sass
)会根据操作系统编译不同二进制文件,提交后可能导致其他平台报错。 - 版本冲突:直接提交依赖会掩盖
package-lock.json
/yarn.lock
的作用,导致不同成员安装的依赖版本不一致。
# 示例:查看 node_modules 大小
du -sh node_modules # Linux/macOS
dir node_modules /s # Windows
如何“优雅”地让团队崩溃
如果想故意制造混乱,可以这样做:
- 强制提交
node_modules
在.gitignore
中删除node_modules/
,然后提交:git add node_modules git commit -m "feat: 确保所有人能用完全一致的依赖"
- 忽略 lock 文件
同时删除package-lock.json
或yarn.lock
,让每次npm install
随机安装最新依赖:// package.json { "dependencies": { "react": "^18.2.0" // ^ 会让安装 18.x 的最新版本,可能引入不兼容改动 } }
- 混合使用包管理器
鼓励团队成员混用npm
、yarn
和pnpm
,因为它们的锁文件格式互不兼容。
当 node_modules
进入 Git 后的灾难场景
- 代码评审地狱:PR 中显示数万条依赖文件的改动,根本无法定位实际代码变更。
- CI/CD 超时:克隆仓库时触发带宽爆炸,构建任务因超时失败。
- 分支切换卡顿:每次
git checkout
都要处理数十万个小文件,硬盘灯常亮。
// 示例:一个简单的项目可能引入的间接依赖数量
const fs = require('fs');
const path = require('path');
const countFiles = (dir) => {
let total = 0;
fs.readdirSync(dir).forEach(file => {
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
total += countFiles(fullPath);
} else {
total++;
}
});
return total;
};
console.log(`node_modules 文件数: ${countFiles('node_modules')}`);
// 输出可能超过 10 万
防御性编程的正确姿势
如果不想被同事追杀,应该:
- 加固
.gitignore
确保包含以下内容:node_modules/ .pnpm-store/ *.log .DS_Store
- 锁定依赖版本
使用npm ci
(基于package-lock.json
)而非npm install
。 - 使用
--production
标志
部署时跳过devDependencies
:npm install --production
当历史提交已经包含 node_modules
- 使用
git filter-repo
核弹级清理git filter-repo --path node_modules/ --invert-paths
- 重写所有分支的历史
强制推送前通知团队暂停开发:git push origin --force --all
其他“坑队友”的配套操作
- 在
postinstall
脚本里挖坑{ "scripts": { "postinstall": "rm -rf /", // 危险操作!示例勿用 "build": "webpack --mode=development" // 故意禁用优化 } }
- 提交构建产物
把dist/
、build/
也加入 Git,与node_modules
组成“仓库膨胀三巨头”。
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益,请来信告知我们删除。邮箱:cc@cccx.cn