Skip to content

Claude Code 最佳实践

围绕「管理上下文窗口」这一核心约束,提炼出的高效使用模式。

是什么

Claude Code 是一个具备自主能力的 agentic 编码环境:它能读文件、跑命令、改代码,并在你观察、纠偏或离开时自主推进问题。与聊天机器人不同,你描述想要什么,Claude 负责探索、规划与实现。

本文汇总了 Anthropic 内部团队及大量工程师在各种代码库、语言、环境中验证有效的实践。绝大多数最佳实践都源自同一个约束:Claude 的上下文窗口会很快被填满,而上下文越满,LLM 表现越差——因此上下文是最重要、需要主动管理的资源。

怎么工作

  • 给 Claude 一个可自行运行的「验证手段」(测试、构建退出码、linter、对比 fixture 的脚本、对比设计稿的浏览器截图),让它能自闭环地迭代到通过为止,而不是让你充当验证循环。
  • 让 Claude 用证据说话:展示测试输出、运行的命令及其返回、或结果截图,而不仅声称「成功」。
  • 先探索、再规划、后编码:用 plan mode 把研究/规划与实现分开,避免解错问题;推荐 Explore → Plan → Implement → Commit 四阶段。
  • 在 prompt 中给出具体上下文:指明文件、说明约束、指向示例模式;用 @ 引用文件、直接粘贴截图、或 cat error.log | claude 管道喂数据。
  • 写好 CLAUDE.md:/init 生成起点后持续精炼;保持简短、只放普遍适用的内容,按「删掉它会不会让 Claude 出错」逐行筛。
  • 配置环境:用 auto mode / /permissions 白名单 / /sandbox 减少授权打断;让 Claude 使用 ghawsgcloud 等 CLI 工具;用 claude mcp add 接外部工具;用 hooks 保证「每次必做」的动作。
  • 积极管理上下文:不相关任务之间用 /clear;同一问题纠正超过两次就 /clear 重开并写更好的 prompt;接近上限时自动 compact,也可 /compact <instructions>
  • 用 subagent 做调研与验证:它在独立上下文中探索并回报摘要,不污染主对话。
  • 利用 checkpoint:每个 prompt 都建检查点,/rewind 或双击 Esc 可恢复对话/代码/两者,可大胆尝试风险方案。
  • 自动化与横向扩展:用 claude -p 非交互模式接入 CI/脚本,跑多会话并行(worktrees / 桌面端 / web / agent teams),按文件 fan-out 批量迁移。
  • 加一道对抗式 review:让 fresh-context 的 subagent 只看 diff 和验收标准来挑漏洞,但只关注影响正确性或既定需求的 gap,避免过度工程。

怎么配置 / 用法

推荐的探索→规划→实现→提交工作流(plan mode 内外切换):

txt
# Explore(plan mode)
read /src/auth and understand how we handle sessions and login.
also look at how we manage environment variables for secrets.

# Plan(plan mode,Ctrl+G 可在编辑器中改计划)
I want to add Google OAuth. What files need to change?
What's the session flow? Create a plan.

# Implement(default mode)
implement the OAuth flow from your plan. write tests for the
callback handler, run the test suite and fix any failures.

# Commit(default mode)
commit with a descriptive message and open a PR

CLAUDE.md 示例(保持简短、可被 git 共享,可用 @path 导入其他文件):

markdown
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')

# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance

非交互模式与按文件 fan-out 批量处理:

bash
# 一次性查询
claude -p "Explain what this project does"

# 脚本用结构化输出
claude -p "List all API endpoints" --output-format json

# 实时流式处理
claude -p "Analyze this log file" --output-format stream-json --verbose

# 循环 fan-out,用 --allowedTools 限定权限
for file in $(cat files.txt); do
  claude -p "Migrate $file from React to Vue. Return OK or FAIL." \
    --allowedTools "Edit,Bash(git commit *)"
done

# auto mode 无人值守执行
claude --permission-mode auto -p "fix all lint errors"

什么时候用

  • 用 plan mode:方案不确定、改动跨多文件、或对要改的代码不熟悉时;若能一句话描述 diff(如改 typo、加日志、重命名变量)则跳过规划直接做。
  • 上手新代码库时把 Claude 当资深工程师提问(日志怎么走、如何新建 API endpoint、某行代码为何这样写)。
  • 做较大特性前,让 Claude 用 AskUserQuestion 工具先「采访」你,产出 SPEC.md,再开新会话执行。
  • 需要研究/验证又不想污染主上下文时,委派给 subagent。
  • 大规模迁移或分析时用 claude -p fan-out,并接入 CI、pre-commit、数据处理管线。

限制 / 坑

  • Checkpoints 只追踪 Claude 自身做的更改,不含外部进程,不能替代 git。
  • Stop hook 会阻止回合结束直到检查通过,但 Claude Code 在连续 8 次阻止后会覆盖该 hook 并结束回合。
  • auto mode 在 -p 非交互运行下,若分类器反复拦截会直接中止(无人可回退)。
  • 对抗式 reviewer 即便代码无问题也常会报出一些 gap,盲目追逐每条会导致过度工程;应只处理影响正确性/需求的部分。
  • CLAUDE.md 过长会使重要规则被淹没、被 Claude 忽略,需要持续修剪。

硬事实速查(12 条)

  • /init 会分析代码库(构建系统、测试框架、代码模式)生成起步版 CLAUDE.md。
  • CLAUDE.md 每次会话开头都会加载;可用 @path/to/import 语法导入其他文件;可加 IMPORTANT / YOU MUST 等强调以提高遵从度。
  • CLAUDE.md 可放多处:~/.claude/CLAUDE.md(全局)、./CLAUDE.md(入 git 共享)、./CLAUDE.local.md(个人,应加入 .gitignore)、父/子目录(monorepo 自动/按需加载)。
  • 减少授权打断三种方式:auto mode(分类器模型审查命令)、/permissions 白名单具体命令、/sandbox 做 OS 级隔离。
  • Skills 放在 .claude/skills/<name>/SKILL.md(带 name/description front-matter),自动按需加载或用 /skill-name 调用;带副作用的工作流用 disable-model-invocation: true 改为手动触发(如 /fix-issue 1234)。
  • Subagents 定义在 .claude/agents/*.md,可声明 tools 与 model,运行在独立上下文;显式让 Claude 调用。
  • Hooks 是确定性的(CLAUDE.md 仅为建议性):编辑 .claude/settings.json 配置,/hooks 浏览,Claude 也能帮你写 hook。
  • claude mcp add 连接 Notion、Figma、数据库等外部工具;安装 gh CLI 让 Claude 高效操作 GitHub 并避免未认证请求的限流。
  • 会话纠偏:Esc 中断(保留上下文)、Esc+Esc/rewind 打开回退菜单、说「Undo that」让其撤销、/clear 重置上下文。
  • 上下文管理:自动 compaction、/compact <instructions> 定向压缩、Esc+Esc 选检查点做 Summarize from/up to here、/btw 提问不进入对话历史。
  • 会话可持久恢复:claude --continue 继续最近一次、claude --resume 从列表选择、/rename 给会话取名(如 oauth-migration)当作分支管理。
  • 并行与扩展手段:worktrees、桌面 app、Claude Code on the web、agent teams;内置 /code-review skill 在 fresh subagent 中复查 diff 找 bug。

官方出处:https://code.claude.com/docs/en/best-practices