Claude Code 最佳實踐
進階工作流程優化、自動化技巧與效能調優的完整實戰指南。
Plan Mode 工作流程最佳化
建立高效的開發工作流程,從探索、規劃到實作的完整週期。
Explore-Plan-Code 工作流程
1. Explore 探索
- 分析現有程式碼
- 了解專案結構
- 識別改進機會
2. Plan 規劃
- 制定實作策略
- 設計架構方案
- 評估風險與依賴
3. Code 實作
- 撰寫高品質程式碼
- 執行測試驗證
- 持續重構優化
測試驅動開發(TDD)
透過 TDD 方法論,確保程式碼品質與可維護性。
TDD 循環
基礎概念
1. 表格序列化(Table Serialization)
當你需要提供表格數據給 Claude 時,直接貼上表格的視覺呈現可能會讓它混淆。最好的方式是將表格「序列化」,轉換成純文字格式。
2. 使用 XML 標籤
使用 XML 標籤(如 <context>、<code>、<instructions>)可以清晰地劃分提示的不同部分。
這是一個 Python 函式,它接收一個數字列表並返回偶數。
def get_evens(numbers):
return [num for num in numbers if num % 2 == 0]
請幫我為這個函式加上文件字串。<context> 這裡有一個 Python 函式... </context> <code> def get_evens(numbers): ... </code> <instructions> 請為 <code> 標籤中的函式加上 Google 風格的 docstring。 </instructions>
3. 任務拆解(Decomposition)
面對複雜問題時,不要試圖一步到位。將大問題拆解成一系列更小、更簡單的子任務。
Hooks:工具執行生命週期管控
Hooks 是用戶定義的 shell 命令,在 Claude Code 的不同生命週期點自動執行,提供對 Claude 行為的確定性控制。
執行流程演示
Write 工具如何創建 Hooks
快速開始
- 1執行
/hooksslash 命令 - 2選擇 hook 事件(PreToolUse、PostToolUse、Notification、Stop)
- 3添加 matcher(如 「Bash」或「*」)
- 4輸入 hook 命令並保存配置
TypeScript 類型檢查自動修復
tsc --noEmit,擷取類型錯誤並回饋給 Claude,讓 Claude 自動修正確保程式碼無類型錯誤。{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "tsc --noEmit 2>&1 || echo 'TypeScript 檢查完成'"
}
]
}
]
}
}- Claude 修改 TypeScript 檔案(Write/Edit/MultiEdit)
- Hook 自動執行
tsc --noEmit - 如果有類型錯誤,錯誤訊息會顯示在 Claude 對話中
- Claude 看到錯誤後會自動修正相關程式碼
Prettier 自動格式化
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "npx prettier --write . || echo 'Prettier 格式化完成 ✨'"
}
]
}
]
}
}ESLint 程式碼檢查
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "tsc --noEmit 2>&1 && eslint . --ext .ts,.tsx || echo '程式檢查完成 ✅'"
}
]
}
]
}
}- 先執行 TypeScript 類型檢查(
tsc --noEmit) - 若無錯誤,再執行 ESLint 檢查(
eslint . --ext .ts,.tsx) - 任一檢查失敗都會顯示錯誤訊息給 Claude
Sub-agents:委派任務給專家
將 subagent 視為您預先定義的專家團隊。主智能體可以將特定工作交給最擅長該領域的 subagent 處理。
Subagents 串聯協作(Chaining subagents)
創建專業化的工作流程,讓多個 subagents 協同完成複雜任務。每個 agent 專精不同領域,串聯後發揮最大效益。
創建專業 Subagents
使用 /agents 指令創建專業化的 subagents,讓它們成為您的專屬技術團隊。
/agents開啟 subagent 創建介面Code Reviewer
專家級程式碼審查專家,主動審查程式碼品質、安全性和可維護性。
--- name: code-reviewer description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code. tools: Read, Grep, Glob, Bash --- You are a senior code reviewer ensuring high standards of code quality and security. When invoked: 1. Run git diff to see recent changes 2. Focus on modified files 3. Begin review immediately Review checklist: - Code is simple and readable - Functions and variables are well-named - No duplicated code - Proper error handling - No exposed secrets or API keys - Input validation implemented - Good test coverage - Performance considerations addressed Provide feedback organized by priority: - Critical issues (must fix) - Warnings (should fix) - Suggestions (consider improving) Include specific examples of how to fix issues.
Debugger
錯誤、測試失敗和意外行為的除錯專家。
--- name: debugger description: Debugging specialist for errors, test failures, and unexpected behavior. Use proactively when encountering any issues. tools: Read, Edit, Bash, Grep, Glob --- You are an expert debugger specializing in root cause analysis. When invoked: 1. Capture error message and stack trace 2. Identify reproduction steps 3. Isolate the failure location 4. Implement minimal fix 5. Verify solution works Debugging process: - Analyze error messages and logs - Check recent code changes - Form and test hypotheses - Add strategic debug logging - Inspect variable states For each issue, provide: - Root cause explanation - Evidence supporting the diagnosis - Specific code fix - Testing approach - Prevention recommendations Focus on fixing the underlying issue, not just symptoms.
- 工具權限控制:限制 subagent 只能使用特定工具,提高安全性
- 版本控制整合:將專案級 subagents 加入 Git,團隊共享使用
- 自動委派:讓 Claude 根據任務內容自動選擇合適的 subagent
最佳實踐
- Start with Claude-generated agents:讓 Claude 生成初始 subagent,再根據需求客製化
- Design focused subagents:單一職責原則,避免讓一個 agent 做所有事情
- Write detailed prompts:提供具體指令、範例和約束條件
- Limit tool access:只給予必要的工具權限,提升安全性和專注度
- Version control:將專案級 subagents 加入版本控制,團隊協作共享
Git 操作輔助
超過 90% 的 Git 任務可透過 Claude 完成,有效降低記憶 CLI 指令的負擔。
Git 歷史查詢
- 「哪些變更被納入 v1.2.3?」
- 「這段功能是誰維護的?」
- 「這個 API 為什麼是這樣設計?」
智能 Commit Message
自動分析修改內容與上下文,產出精確且具描述性的 commit 訊息。
進階 Git 操作
- 還原特定檔案
- 解決 rebase 衝突
- 比對與移植 patch
上下文分析
Claude 理解專案結構,提供更精準的 Git 操作建議與自動化處理。
點擊按鈕,模擬向 Claude 下達指令:
在與 GitHub 整合的場景中,Claude 能處理大多數常見協作操作,加速開發與 code review 流程。
建立 PR
Claude 能理解「pr」這類縮寫,並根據差異與上下文撰寫合適的 PR 描述。
一鍵解決 Review
告訴 Claude 修正評論,它會修改後直接推回對應的 PR 分支。
處理建置失敗
協助處理 CI/CD 建置失敗、Linter 警告等問題。
Issues 分類標註
逐一檢視並標記 GitHub issues,節省 triage 時間。
實際操作範例
B. Gates commented
Please add a `try...except` block to handle potential `KeyError`.
def get_user_name(data):
return data["user"]["name"]平行運作 Claude
最強大的應用之一,就是平行運行多個 Claude 實例,以拆分上下文、提升效率。
你可以讓一個 Claude 撰寫程式,另一個驗證或測試它的輸出,第三個再進行優化。
使用 Git Worktree 實現真正的平行開發:在同一專案的不同分支上同時運行多個 Claude Code 會話,並行開發不同方案,最後選擇表現最優的合併回來。
核心優勢
- 避免分支切換時的上下文丟失
- 多個 Claude 會話可同時處理不同功能
- 並行開發後比較選擇最佳方案
- 提升開發效率與程式碼品質
Git Worktree 並行開發完整流程
為不同實作方案建立獨立工作目錄
同時使用多個 Claude 會話開發不同方案
測試並比較各方案的效能與品質
選擇最佳方案合併回主分支
實際操作指令
git worktree add ../project-auth-v1 feature/auth-v1 git worktree add ../project-auth-v2 feature/auth-v2
cd ../project-auth-v1 && claude & cd ../project-auth-v2 && claude &
git diff feature/auth-v1 feature/auth-v2 git checkout main && git merge feature/auth-v2
學習成果測驗
什麼是 Claude Code 的 Plan Mode 最核心的價值?
使用 Sub-agents 進行任務分解的最佳時機是?
Git Worktree 與 Claude Code 結合的主要優勢是什麼?
Hooks 在 Claude Code 中的主要作用是?
在 Explore-Plan-Code 工作流程中,Explore 階段的重點是?