如何用 .gitignore 排除 git 索引(包括已提交和未提交)

不知道你有没有遇到过这种情况:项目引入了某个包,或者静态网站生成器生成了大量静态文件,但是忘记提前排除掉,导致 git 索引了大量不需要的文件,甚至已经提交并推送到远程仓库里。

如何排除非必要文件的索引?我们可以分情况处理。

情况一:文件还没提交,只是 git add

例如忘记排除 node_modules

# 修改 .gitignore
echo "node_modules/" >> .gitignore

# 从暂存区移除
git rm -r --cached node_modules

# 重新提交
git add .
git commit -m "fix: ignore node_modules"

--cached 的作用是只从 Git 索引中删除,不删除本地文件

情况二:已经提交过了

1. 先更新 .gitignore

例如:

node_modules/
dist/
.idea/
.vscode/
*.log

2. 将已被跟踪的文件从 Git 索引移除

单个目录:

git rm -r --cached node_modules
git rm -r --cached dist

单个文件:

git rm --cached config.local.json

3. 提交变更

git commit -m "chore: remove ignored files from repository"

这样仓库中会删除这些文件,但本地仍然保留。

情况三:已经提交很多文件,想一次性让 .gitignore 生效

最方便的方法:

# 删除所有索引
git rm -r --cached .

# 按新的 .gitignore 重新加入
git add .

git commit -m "chore: apply gitignore"

执行后:

  • Git 会重新扫描项目
  • .gitignore 中匹配的文件不会再被跟踪
  • 本地文件不会被删除

常用检查命令

查看当前被 Git 跟踪的文件:

git ls-files

查看被 .gitignore 忽略的文件:

git status --ignored

查看某个文件是否被 .gitignore 命中:

git check-ignore -v node_modules/test.js

最常用的一套命令

如果你只是「初始化之后忘记写 .gitignore,现在想补上」:

# 编辑 .gitignore

git rm -r --cached .
git add .
git commit -m "apply gitignore rules"

这通常是最省事的做法。

建议尽量在空目录里初始化 git,并第一时间创建 .gitignore 文件,把不需要的目录和文件都写进去。后期如果需要安装包,也要把对应目录添加到 .gitignore 中,推送前提醒自己多检查一步。

耕读君
耕读君

一个筋斗十万八千里,说明上云好啊

文章: 235

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注