> ## Content Index
> Fetch the complete content index at: https://blog.anthea.day/llms.txt
> Use this file to discover other available public pages before exploring further.

# 如何在 local 設置 Git Pre-commit Hook
- URL: https://blog.anthea.day/git-pre-commit-hook-local-setup/
- Published: 2025-05-15T17:30:46.000Z
- Updated: 2026-11-07T20:07:49.000Z
- Author: Anthea / 芫荽
- Tags: #Migrated-1792241843742, #Import 2026-10-17 12:57, Coding

### 什麼是 Pre-commit Hook

Git pre-commit hook 是一種本地腳本，在跑 git commit 命令時會自動執行。這些 hook 可以用來確保程式碼品質，例如 run test、TypeScript 型別檢查、執行 ES Lint 等等，確保只有合格的程式碼才能被提交。

#### Local Hook 的好處

- 只影響 local，不會干擾其他團隊成員 → 以我們團隊來說，因為每個人電腦規格不同，如果大家 commit 前都需要跑過一次測試可能會很沒有效率，所以我選擇只寫在自己的 local 上
- 不需要修改專案的 package.json
- 不會被提交到版本庫
- 可以根據個人需求自定義檢查內容

---

### 設置步驟

1\. 建立 hooks 目錄

```bash
mkdir -p .git/hooks
```

2\. 建立 pre-commit 檔案

```bash
touch .git/hooks/pre-commit
```

3\. 編寫 pre-commit 腳本，將以下內容寫入 .git/hooks/pre-commit 檔案：

```bash
#!/bin/sh 
echo "Running pre-commit hook: tests and type checking..." 
 
# Exit on error 
set -e 
 
# Run tests 
echo "Running tests..." 
npm run test 
 
# Run type checking 
echo "Running type checking..." 
npm run tsc 
 
echo "All checks passed! Proceeding with commit."
```

4\. 設定執行權限

```bash
chmod +x .git/hooks/pre-commit
```

#### 測試與使用

建立一個測試 commit：

```sql
git add . 
git commit -m "Test commit"
```

如果設置正確，執行後就會看到測試與 TypeScript 型別檢查完後才會真的 commit 成功。

如果需要臨時跳過 hook 檢查：

```sql
git commit --no-verify
```

---

### Q&A

**如果我設定了這個 pre-commit 的內容，是不是連後端專案的 commit 都會跑過這個 pre-commit？**

pre-commit hook 是儲存在每個 Git 儲存庫的 `.git/hooks` 目錄中，只對該特定儲存庫有效。

所以說，我們在哪個專案中設定的 pre-commit hook：

1. 只會在對這個專案進行 commit 時執行
2. 不會影響電腦上的其他專案（如後端專案）
3. 每個 Git 儲存庫都有自己獨立的 hooks 設定