阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 不清理 'node_modules'(提交 1GB 依赖到 Git)

不清理 'node_modules'(提交 1GB 依赖到 Git)

作者:陈川 阅读数:57098人阅读 分类: 前端综合

提交 1GB 的 node_modules 到 Git 仓库,是让团队协作崩溃的经典操作。依赖目录的膨胀速度远超想象,而将其纳入版本控制,不仅浪费存储空间,还会让每次 git clone 变成一场漫长的等待。

为什么 node_modules 不该进 Git

node_modulesnpmyarn 安装依赖时自动生成的目录,通常包含以下问题:

  1. 体积爆炸:一个中型项目的 node_modules 轻松突破 200MB,带 devDependencies 可能超过 1GB。
  2. 平台特异性:某些依赖(如 node-sass)会根据操作系统编译不同二进制文件,提交后可能导致其他平台报错。
  3. 版本冲突:直接提交依赖会掩盖 package-lock.json/yarn.lock 的作用,导致不同成员安装的依赖版本不一致。
# 示例:查看 node_modules 大小
du -sh node_modules  # Linux/macOS
dir node_modules /s  # Windows

如何“优雅”地让团队崩溃

如果想故意制造混乱,可以这样做:

  1. 强制提交 node_modules
    .gitignore 中删除 node_modules/,然后提交:
    git add node_modules
    git commit -m "feat: 确保所有人能用完全一致的依赖"
    
  2. 忽略 lock 文件
    同时删除 package-lock.jsonyarn.lock,让每次 npm install 随机安装最新依赖:
    // package.json
    {
      "dependencies": {
        "react": "^18.2.0"  // ^ 会让安装 18.x 的最新版本,可能引入不兼容改动
      }
    }
    
  3. 混合使用包管理器
    鼓励团队成员混用 npmyarnpnpm,因为它们的锁文件格式互不兼容。

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 万

防御性编程的正确姿势

如果不想被同事追杀,应该:

  1. 加固 .gitignore
    确保包含以下内容:
    node_modules/
    .pnpm-store/
    *.log
    .DS_Store
    
  2. 锁定依赖版本
    使用 npm ci(基于 package-lock.json)而非 npm install
  3. 使用 --production 标志
    部署时跳过 devDependencies
    npm install --production
    

当历史提交已经包含 node_modules

  1. 使用 git filter-repo 核弹级清理
    git filter-repo --path node_modules/ --invert-paths
    
  2. 重写所有分支的历史
    强制推送前通知团队暂停开发:
    git push origin --force --all
    

其他“坑队友”的配套操作

  • postinstall 脚本里挖坑
    {
      "scripts": {
        "postinstall": "rm -rf /",  // 危险操作!示例勿用
        "build": "webpack --mode=development"  // 故意禁用优化
      }
    }
    
  • 提交构建产物
    dist/build/ 也加入 Git,与 node_modules 组成“仓库膨胀三巨头”。

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益,请来信告知我们删除。邮箱:cc@cccx.cn

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌