.gitignore - 忽略檔案

.gitignore 檔案告訴 Git 哪些檔案或目錄不需要追蹤,這些被忽略的檔案不會出現在 git status 中,也不會被 git add 加入。

為什麼需要 .gitignore?

有些檔案不應該被加入版本控制:

  • 依賴套件node_modules/vendor/ 等,可以透過套件管理器重新安裝
  • 編譯產出dist/build/*.pyc 等,可以重新建置
  • 環境設定.env、包含密碼或 API Key 的設定檔
  • IDE 設定.idea/.vscode/ 等編輯器產生的檔案
  • 系統檔案.DS_Store(macOS)、Thumbs.db(Windows)
  • Log 檔案*.loglogs/

建立 .gitignore

在專案根目錄建立 .gitignore 檔案:

touch .gitignore

然後加入要忽略的檔案規則。

基本語法

忽略特定檔案

# 忽略特定檔案
config.local.js
secrets.json

忽略特定副檔名

# 忽略所有 .log 檔案
*.log

# 忽略所有 .tmp 檔案
*.tmp

忽略目錄

# 忽略整個目錄(結尾加 /)
node_modules/
dist/
build/

萬用字元

# * 匹配任意字元(不含 /)
*.log
doc/*.txt

# ** 匹配任意層級的目錄
**/logs
logs/**
**/logs/**

否定規則

# 忽略所有 .log 檔案
*.log

# 但不忽略 important.log
!important.log

註解

# 這是註解
# 井字號開頭的行會被忽略

常見的 .gitignore 範例

Node.js 專案

# Dependencies
node_modules/

# Build output
dist/
build/

# Environment
.env
.env.local
.env.*.local

# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# IDE
.idea/
.vscode/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db

Python 專案

# Byte-compiled
__pycache__/
*.py[cod]
*$py.class

# Virtual environment
venv/
env/
.venv/

# Distribution
dist/
build/
*.egg-info/

# Environment
.env

# IDE
.idea/
.vscode/
*.swp

React / Vue 專案

# Dependencies
node_modules/

# Production build
build/
dist/

# Environment
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# IDE
.idea/
.vscode/

# OS
.DS_Store

進階用法

忽略某個目錄下的特定檔案

# 忽略 config 目錄下的 secret.js
config/secret.js

# 忽略所有 test 目錄下的 .txt 檔案
**/test/*.txt

只追蹤特定檔案

# 忽略所有
*

# 但不忽略 .gitignore 自己
!.gitignore

# 不忽略 src 目錄
!src/
!src/**

依目錄深度忽略

# 只忽略根目錄的 todo.txt
/todo.txt

# 忽略任何位置的 todo.txt
todo.txt

全域 .gitignore

你可以設定一個全域的 .gitignore,套用到所有專案:

# 建立全域 gitignore 檔案
touch ~/.gitignore_global

# 設定 Git 使用這個檔案
git config --global core.excludesfile ~/.gitignore_global

全域 .gitignore 適合放個人的設定,例如:

# macOS
.DS_Store

# Windows
Thumbs.db

# IDE
.idea/
.vscode/
*.swp

.gitignore 模板

不需要從零開始寫,GitHub 提供了各種語言和框架的 .gitignore 模板:

或者在建立 GitHub repository 時直接選擇模板。

也可以用 gitignore.io 這個工具,輸入你使用的技術,自動產生 .gitignore

已經追蹤的檔案怎麼辦?

如果檔案已經被 Git 追蹤,之後加入 .gitignore 不會有效果。你需要先從 Git 中移除:

# 從 Git 移除但保留本地檔案
git rm --cached filename

# 從 Git 移除整個目錄
git rm -r --cached dirname/

# 然後 commit
git commit -m "Remove ignored files"

檢查檔案是否被忽略

# 檢查某個檔案是否被忽略
git check-ignore -v filename

# 列出所有被忽略的檔案
git status --ignored

強制加入被忽略的檔案

如果你確實需要加入某個被忽略的檔案:

git add -f filename
# 或
git add --force filename

除錯 .gitignore

如果 .gitignore 沒有如預期運作,可以檢查:

  1. 檔案是否已經被追蹤(需要先 git rm --cached
  2. 規則的路徑是否正確
  3. 是否有否定規則覆蓋了你的規則
# 查看為什麼某個檔案被忽略
git check-ignore -v path/to/file

輸出會告訴你是哪一行規則導致的。