.gitignore 是 Git 版本控制中非常重要的設定檔,用來告訴 Git 哪些檔案或目錄不需要被追蹤(track)。這些通常是編譯產生的暫存檔、相依套件目錄、個人 IDE 設定、環境變數檔案等,不應該被提交到版本庫中。
為什麼需要 .gitignore?
- 避免提交不必要的檔案:
node_modules、__pycache__ 等體積龐大的目錄
- 保護敏感資訊:
.env 檔案中可能包含資料庫密碼、API 金鑰
- 避免衝突:IDE 的
.vscode、.idea 設定檔因人而異,提交會造成干擾
- 保持倉庫乾淨:只追蹤真正重要的程式碼
.gitignore 語法規則
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# 這是註解,以 # 開頭
# 忽略特定檔案
secret.txt
# 忽略特定副檔名(萬用字元)
*.log
*.tmp
*.swp
# 忽略特定目錄(以 / 結尾)
node_modules/
dist/
build/
# 忽略特定目錄下的特定檔案
logs/*.log
# 忽略所有子目錄中的 .DS_Store
**/.DS_Store
# 排除規則(以 ! 開頭,表示「不忽略」)
*.log
!important.log # 即使副檔名是 .log,important.log 仍會被追蹤
# 忽略根目錄下的 TODO,但不忽略子目錄的 TODO
/TODO
|
常見需要忽略的檔案類型
Node.js 專案
1
2
3
4
5
6
7
|
node_modules/
npm-debug.log*
yarn-error.log
.env
.env.local
dist/
build/
|
Python 專案
1
2
3
4
5
6
7
8
9
|
__pycache__/
*.py[cod]
*.egg-info/
.venv/
venv/
.env
dist/
build/
*.log
|
IDE 和編輯器設定
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# VS Code
.vscode/
!.vscode/extensions.json # 但保留推薦的擴充套件清單
# JetBrains (IntelliJ, PyCharm, WebStorm 等)
.idea/
# Vim
*.swp
*.swo
# macOS
.DS_Store
|
環境變數檔案
1
2
3
4
5
|
.env
.env.local
.env.*.local
.env.development
.env.production
|
使用 gitignore.io 自動產生
gitignore.io(現為 toptal.com/developers/gitignore)是一個很方便的線上工具,可以根據你的技術棧自動生成完整的 .gitignore 內容。
透過網頁使用
- 前往 gitignore.io
- 輸入你使用的技術(如
Node、Python、macOS、VisualStudioCode)
- 點擊「Create」按鈕
- 複製產生的內容到你的
.gitignore 檔案
透過命令列使用
1
2
3
4
5
|
# 產生 Node.js + macOS 的 .gitignore
curl -sL https://www.toptal.com/developers/gitignore/api/node,macos > .gitignore
# 產生 Python + Linux 的 .gitignore
curl -sL https://www.toptal.com/developers/gitignore/api/python,linux > .gitignore
|
已追蹤的檔案要如何忽略?
如果某個檔案已經被 git 追蹤了,即使加入 .gitignore 也不會立即生效,需要先從追蹤中移除:
1
2
3
4
5
6
7
8
9
|
# 從 Git 追蹤中移除,但保留實體檔案
git rm --cached 檔案名稱
# 移除整個目錄
git rm -r --cached 目錄名稱/
# 然後提交這個變更
git add .gitignore
git commit -m "Remove tracked files that should be ignored"
|
PhoneGap/Cordova 專案的 .gitignore
PhoneGap/Cordova 專案常見的忽略設定:
1
2
3
4
5
6
7
8
9
10
11
|
# Cordova plugins
plugins/
# Platform-specific builds
platforms/
# npm 相依套件
node_modules/
# build 產物
www/lib/
|
參考資料