切换·Esc 返回

忽略文件.gitignore

Git 专区
告诉 Git 哪些新文件不要记录

.gitignore 常用来排除依赖、构建产物、本地系统文件和 .env。它只影响尚未跟踪的文件,不能自动移除旧提交中的内容;密钥一旦泄露,还需要立即轮换。

工作区index.html 和 .env .gitignore 暂存区只有 index.html
$ echo ".env" >> .gitignore
写进 .gitignore 的未跟踪文件不会进暂存区和历史。已经提交过的要先 git rm --cached 停止跟踪;密钥一旦进过历史就按泄露处理

什么时候用

  • 新项目第一件事建 .gitignore,再开始第一次 提交 Commit
    .gitignore
    node_modules/
    .next/
    .env
    .DS_Store
    匹配规则且尚未跟踪的文件会被忽略
  • 排除 node_modules 等能根据项目配置重新生成的内容
    $ git statusworking tree cleannode_modules 装了 380MB,仓库里看不见
  • 排除真实密钥文件,并提交不含真值的示例配置
    .env🔒 只在你电脑上
    Key 留在本地,云端仓库干干净净
  • 参考官方或社区模板后,再按当前项目调整规则
    Add .gitignoreNode
    模板库:github.com/github/gitignore

什么时候不用

  • 把依赖目录提交到仓库,增加体积并制造无关差异
    node_modules 380MBgit push →
    几百 MB 垃圾进仓库,该进 .gitignore
  • .env 进去了以为删掉就行:历史里还躺着,先重置 Key 再清历史
    .env 已经 push 上去了!
    ① 立刻去平台重置 Key
    ② 用 BFG / filter-repo 清历史
    只删文件没用,历史里还躺着
  • 文件已经被跟踪后才补规则;还要另外停止跟踪
    .env 提交过了,才补写进 .gitignore…$ git statusmodified: .env已跟踪的不认 .gitignore,要 git rm --cached
  • 图省事在 .gitignore 里写 *:新写的页面也进不了仓库
    .gitignore
    *
    图省事全忽略,新写的页面也进不了仓库
组成结构 · Anatomy
.gitignore node_modules/ 依赖目录,npm install 随时装回来 .next/ 构建产物,npm run build 会重新生成 .env 密钥文件,见 {c:env-var},绝不能进仓库 .DS_Store mac 系统垃圾,跟代码毫无关系
1依赖目录node_modules/几百 MB 的第三方包,package.json 在就能一键装回
2构建产物.next/打包生成的结果,每次 build 都会重新产出
3本地配置.env可能包含 API 密钥等敏感配置,不应提交到仓库
4系统垃圾.DS_Store操作系统自动生成的小文件,与代码无关
常见变体 · Variants
精确点名Exact
.env
指名道姓忽略某一个文件
整个目录Directory
node_modules/
末尾加斜杠,忽略整个文件夹
通配一类Wildcard
*.log
同后缀的一类文件全部忽略
网开一面Negate
!keep.log
感叹号开头,把这个例外捞回来
典型使用场景
新建 .gitignore 文件
.gitignore
node_modules/ # 依赖,能装回来
.next/ # 构建产物
.env # 密钥,绝不能进
.DS_Store # mac 系统垃圾
git status 前后对比
zsh — my-first-page
# 没写 .gitignore 时: $ git status Untracked: node_modules/ .next/ .env .DS_Store …(刷屏) # 写好 .gitignore 后: $ git status Changes not staged: modified: index.html 清清爽爽,只剩你真正改的文件
GitHub 模板库
Create a new repository
Add .gitignore Node ▾
💡 已有项目想补模板?去 github.com/github/gitignore,搜 Node 复制整份
.env 泄露补救
⚠ .env 已经 push 上去了
从这一刻起,这把 Key 就当它已经泄露
1
立刻去平台重置 / 吊销这把 Key,换一把新的
2
BFG Repo-Cleaner 或 git filter-repo 清掉历史里的 .env
只删文件再提交没用——历史里还躺着,谁都能翻出来