簡介
Claude Code 是 Anthropic 推出的命令行 AI 編程助手,直接運行在終端中,能夠:
- 讀取、編輯整個代碼庫
- 執行 shell 命令
- 管理 Git 工作流
- 跨文件重構
安裝
npm install -g @anthropic-ai/claude-code
或通過 Homebrew:
brew install claude-code
核心用法
基本對話
claude "幫我優化這個函數的效能"
互動模式
claude
進入互動 REPL 後可以直接對話,Claude 會讀取當前目錄的代碼庫。
指定模型
claude --model claude-sonnet-4-20250514 "explain this codebase"
實用技巧
1. CLAUDE.md 項目規範
在專案根目錄創建 CLAUDE.md,寫入:
- 項目簡介
- 技術棧
- 代碼風格
- 常用指令
Claude 自動讀取這個文件作為系統提示。
2. /compact 釋放上下文
當對話過長時使用 /compact 壓縮歷史,保留關鍵信息。
3. 自訂 Slash Commands
在 ~/.claude/commands/ 下創建 .md 文件即可自訂指令。
4. Git 整合
# 自動生成 commit message
claude "generate a commit message for my staged changes"
# Code Review
claude "review the diff against main"
與 Cursor 的對比
| 特性 | Claude Code | Cursor | |------|------------|--------| | 介面 | 終端 CLI | IDE GUI | | 上下文 | 全代碼庫 | 當前文件 + embedding | | Git | 原生整合 | 基本支援 | | 成本 | API 計費 | 訂閱制 | | 適用場景 | 自動化/CI | 日常編碼 |
最佳實踐
- 小步提交:每次變更後 commit,方便回滾
- 明確指令:具體說明要做什麼,而非模糊描述
- 信任但驗證:AI 生成的代碼一定要 review
- 善用 CLAUDE.md:把項目規範寫清楚,效果差很多