Claude Code 最佳实践 - Claude Code 文档

Best practices for Claude Code - Claude Code Docs

Anthropic Anthropic · Anthropic · 2025-04-18 · Anthropic Engineering ↗

打开互动全文版(逐段中英对照 + 图/公式 + 论文问答)→

摘要 · Abstract

入门指南使用 Claude Code 构建管理配置参考 Agent SDK 新特性资源

Getting startedBuild with Claude CodeAdministrationConfigurationReferenceAgent SDKWhat's NewResources

核心贡献 · Key contributions

局限 · Limitations

论文章节 · Sections(共 41)

全文 · Full text(逐段中英对照)

概述 Overview

入门使用 Claude Code 构建管理配置参考 Agent SDK 新功能资源

Getting startedBuild with Claude CodeAdministrationConfigurationReferenceAgent SDKWhat's NewResources

在本页 On this page

* 在提示词中提供具体上下文

* Provide specific context in your prompts

Claude Code 最佳实践 Best practices for Claude Code

从配置环境到跨并行会话扩展,获取 Claude Code 最大效用的技巧和模式。

Tips and patterns for getting the most out of Claude Code, from configuring your environment to scaling across parallel sessions.

Claude Code 是一个智能体式编码环境。与回答问题和等待的聊天机器人不同,Claude Code 可以读取你的文件、运行命令、进行修改,并在你观察、重定向或完全离开时自主解决问题。这改变了你的工作方式。你不再是自己编写代码然后让 Claude 审查,而是描述你想要什么,Claude 会找出构建方法。Claude 会探索、规划并实现。但这种自主性仍然有一个学习曲线。Claude 在你需要理解的某些约束下工作。本指南涵盖了在 Anthropic 内部团队以及使用 Claude Code 处理各种代码库、语言和环境的工程师中被证明有效的模式。关于智能体循环的内部工作原理,请参阅 Claude Code 的工作原理。

Claude Code is an agentic coding environment. Unlike a chatbot that answers questions and waits, Claude Code can read your files, run commands, make changes, and autonomously work through problems while you watch, redirect, or step away entirely.This changes how you work. Instead of writing code yourself and asking Claude to review it, you describe what you want and Claude figures out how to build it. Claude explores, plans, and implements.But this autonomy still comes with a learning curve. Claude works within certain constraints you need to understand.This guide covers patterns that have proven effective across Anthropic’s internal teams and for engineers using Claude Code across various codebases, languages, and environments. For how the agentic loop works under the hood, see How Claude Code works.

大多数最佳实践都基于一个约束:Claude 的上下文窗口很快就会被填满,并且随着它的填满,性能会下降。Claude 的上下文窗口包含你的整个对话,包括每条消息、Claude 读取的每个文件以及每个命令的输出。然而,这可能会很快被填满。一次调试会话或代码库探索可能会生成并消耗数万个词元。这很重要,因为随着上下文填满,LLM 性能会下降。当上下文窗口快满时,Claude 可能会开始“忘记”早期的指令或犯更多错误。上下文窗口是需要管理的最重要资源。要查看会话在实践中如何被填满,请观看交互式演练,了解启动时加载了什么以及每次文件读取的成本。使用自定义状态行持续跟踪上下文使用情况,并参阅减少词元使用量以获取减少词元使用量的策略。

Most best practices are based on one constraint: Claude’s context window fills up fast, and performance degrades as it fills.Claude’s context window holds your entire conversation, including every message, every file Claude reads, and every command output. However, this can fill up fast. A single debugging session or codebase exploration might generate and consume tens of thousands of tokens.This matters since LLM performance degrades as context fills. When the context window is getting full, Claude may start “forgetting” earlier instructions or making more mistakes. The context window is the most important resource to manage. To see how a session fills up in practice, watch an interactive walkthrough of what loads at startup and what each file read costs. Track context usage continuously with a custom status line, and see Reduce token usage for strategies on reducing token usage.

给 Claude 一个验证工作的方式 ​(https://www.anthropic.com/engineering/claude-code-best-practices#give-claude-a-way-to-verify-its-work)

给 Claude 一个它可以运行的检查:测试、构建、用于比较的截图。这决定了你是全程盯着会话,还是可以放手不管。

Give Claude a check it can run: tests, a build, a screenshot to compare. It’s the difference between a session you watch and one you walk away from.

Claude 在工作看起来完成时就停下来。如果没有可运行的检查,“看起来完成”是唯一可用的信号,你就成了验证循环:每个错误都在等你发现。给 Claude 一个能产生通过或失败结果的东西,循环就会自动闭合。Claude 执行工作、运行检查、读取结果,并迭代直到检查通过。检查可以是任何能在对话中返回 Claude 可读信号的东西:测试套件、构建退出码、代码检查工具、将输出与基准文件进行差异比较的脚本,或者与设计图对比的浏览器截图。

Claude stops when the work looks done. Without a check it can run, “looks done” is the only signal available, and you become the verification loop: every mistake waits for you to notice it. Give Claude something that produces a pass or fail, and the loop closes on its own. Claude does the work, runs the check, reads the result, and iterates until the check passes.The check is anything that returns a signal Claude can read in the conversation: a test suite, a build exit code, a linter, a script that diffs output against a fixture, or a browser screenshot compared against a design.

一旦检查存在,决定它如何严格地控制停止:

Once the check exists, decide how hard it gates the stop:

* 在单次提示中:要求 Claude 在同一消息中运行检查并迭代,如上表所示。

* In one prompt: ask Claude to run the check and iterate in the same message, as in the table above.

* 跨会话:将检查设置为 /goal 条件。一个独立的评估器在每次轮次后重新检查,Claude 持续工作直到条件满足。

* Across a session: set the check as a /goal condition. A separate evaluator re-checks it after every turn and Claude keeps working until it holds.

* 作为确定性门控:一个 Stop 钩子将你的检查作为脚本运行,并阻止轮次结束直到检查通过。Claude Code 会覆盖该钩子,并在连续 8 次阻塞后结束轮次。

* As a deterministic gate: a Stop hook runs your check as a script and blocks the turn from ending until it passes. Claude Code overrides the hook and ends the turn after 8 consecutive blocks.

* 通过第二意见:一个验证子智能体或动态工作流检查其自身发现,让一个新模型尝试反驳结果,这样执行工作的智能体就不是给自己打分的人。

* By a second opinion: a verification subagent or a dynamic workflow that checks its own findings has a fresh model try to refute the result, so the agent doing the work isn’t the one grading it.

每一步都用设置换取注意力。提示版本适用于今天的任何任务。/goal 和 Stop 钩子版本则能让无人值守的运行正确完成,无需你介入。让 Claude 展示证据而非断言成功:测试输出、它运行的命令及其返回结果,或结果的截图。审查证据比自己重新运行验证更快,也适用于你没有观看的会话。

Each step trades setup for attention. The prompt version works on any task today. The /goal and Stop hook versions are what let an unattended run finish correctly without you.Have Claude show evidence rather than asserting success: the test output, the command it ran and what it returned, or a screenshot of the result. Reviewing evidence is faster than re-running the verification yourself, and it works for sessions you weren’t watching.

先探索,再规划,后编码 ​(https://www.anthropic.com/engineering/claude-code-best-practices#explore-first-then-plan-then-code)

将研究与规划同实现分开,以避免解决错误的问题。

Separate research and planning from implementation to avoid solving the wrong problem.

让 Claude 直接跳到编码可能会产生解决错误问题的代码。使用规划模式将探索与执行分开。推荐的工作流程包含四个阶段:

Letting Claude jump straight to coding can produce code that solves the wrong problem. Use plan mode to separate exploration from execution.The recommended workflow has four phases:

进入规划模式。Claude 读取文件并回答问题,不做任何修改。

Enter plan mode. Claude reads files and answers questions without making changes.

读取 /src/auth 并理解我们如何处理会话和登录。

read /src/auth and understand how we handle sessions and login.

同时查看我们如何管理用于秘密的环境变量。

also look at how we manage environment variables for secrets.

要求 Claude 创建详细的实现计划。

Ask Claude to create a detailed implementation plan.

我想添加 Google OAuth。哪些文件需要修改?

I want to add Google OAuth. What files need to change?

在 Claude 继续之前,按 Ctrl+G 在文本编辑器中打开计划进行直接编辑。

Press Ctrl+G to open the plan in your text editor for direct editing before Claude proceeds.

退出规划模式,让 Claude 编码,并根据其计划进行验证。

Switch out of plan mode and let Claude code, verifying against its plan.

根据你的计划实现 OAuth 流程。为回调处理程序编写测试,运行测试套件并修复所有失败。

implement the OAuth flow from your plan. write tests for the

要求 Claude 用描述性消息提交并创建 PR。

callback handler, run the test suite and fix any failures.

用描述性消息提交并打开 PR。

Ask Claude to commit with a descriptive message and create a PR.

规划模式很有用,但也会增加开销。对于范围明确且修复很小的任务(如修复拼写错误、添加日志行或重命名变量),直接让 Claude 去做。当你不确定方法、更改涉及多个文件或你不熟悉要修改的代码时,规划最为有用。如果你能用一句话描述差异,就跳过规划。

commit with a descriptive message and open a PR

Plan mode is useful, but also adds overhead.For tasks where the scope is clear and the fix is small (like fixing a typo, adding a log line, or renaming a variable) ask Claude to do it directly.Planning is most useful when you’re uncertain about the approach, when the change modifies multiple files, or when you’re unfamiliar with the code being modified. If you could describe the diff in one sentence, skip the plan.

在提示中提供具体上下文 ​(https://www.anthropic.com/engineering/claude-code-best-practices#provide-specific-context-in-your-prompts)

指令越精确,需要的修正就越少。

The more precise your instructions, the fewer corrections you’ll need.

Claude 可以推断意图,但无法读取你的想法。请引用特定文件,提及约束条件,并指向示例模式。

Claude can infer intent, but it can’t read your mind. Reference specific files, mention constraints, and point to example patterns.

模糊的提示在探索阶段且能承受方向调整时可能有用。像“你会改进这个文件中的什么?”这样的提示可以揭示你原本不会想到要问的问题。

Vague prompts can be useful when you’re exploring and can afford to course-correct. A prompt like "what would you improve in this file?" can surface things you wouldn’t have thought to ask about.

提供丰富内容 ​(https://www.anthropic.com/engineering/claude-code-best-practices#provide-rich-content)

使用 @ 引用文件、粘贴截图/图像,或直接通过管道传输数据。

Use @ to reference files, paste screenshots/images, or pipe data directly.

你可以通过以下几种方式向 Claude 提供丰富的数据:

You can provide rich data to Claude in several ways:

* 使用 @ 引用文件,而不是描述代码所在位置。Claude 在响应前会读取文件。

* Reference files with @ instead of describing where code lives. Claude reads the file before responding.

* 直接粘贴图像。将图像复制/粘贴或拖放到提示中。

* Paste images directly. Copy/paste or drag and drop images into the prompt.

* 提供文档和 API 参考的 URL。使用 /permissions 将常用域名加入允许列表。

* Give URLs for documentation and API references. Use /permissions to allowlist frequently-used domains.

* 通过运行 cat error.log | claude 将文件内容直接通过管道传输给 Claude。

* Pipe in data by running cat error.log | claude to send file contents directly.

* 让 Claude 自行获取所需内容。告诉 Claude 使用 Bash 命令、MCP 工具或读取文件来拉取上下文。

* Let Claude fetch what it needs. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files.

配置你的环境 ​(https://www.anthropic.com/engineering/claude-code-best-practices#configure-your-environment)

几个设置步骤能让 Claude Code 在你所有会话中显著更有效。关于扩展功能及其使用场景的完整概述,请参阅扩展 Claude Code。

A few setup steps make Claude Code significantly more effective across all your sessions. For a full overview of extension features and when to use each one, see Extend Claude Code.

编写有效的 CLAUDE.md ​(https://www.anthropic.com/engineering/claude-code-best-practices#write-an-effective-claude-md)

运行 /init 可根据当前项目结构生成一个初始的 CLAUDE.md 文件,然后逐步完善。

Run /init to generate a starter CLAUDE.md file based on your current project structure, then refine over time.

CLAUDE.md 是一个特殊文件,Claude 会在每次对话开始时读取它。包含 Bash 命令、代码风格和工作流规则。这为 Claude 提供了无法仅从代码推断出的持久上下文。/init 命令会分析你的代码库,检测构建系统、测试框架和代码模式,为你提供一个坚实的基础进行完善。CLAUDE.md 文件没有固定格式要求,但应保持简短且人类可读。例如:

CLAUDE.md is a special file that Claude reads at the start of every conversation. Include Bash commands, code style, and workflow rules. This gives Claude persistent context it can’t infer from code alone.The /init command analyzes your codebase to detect build systems, test frameworks, and code patterns, giving you a solid foundation to refine.There’s no required format for CLAUDE.md files, but keep it short and human-readable. For example:

代码风格 Code style

- 使用 ES 模块(import/export)语法,而非 CommonJS(require)

- Use ES modules (import/export) syntax, not CommonJS (require)

- 尽可能解构导入(例如 import { foo } from 'bar')

- 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

CLAUDE.md 每次会话都会加载,因此只包含广泛适用的内容。对于仅偶尔相关的领域知识或工作流程,请改用技能。Claude 按需加载它们,不会使每次对话变得臃肿。保持简洁。对于每一行,问自己:“删除这一行会导致 Claude 犯错吗?”如果不是,就删掉。臃肿的 CLAUDE.md 文件会导致 Claude 忽略你的实际指令!

CLAUDE.md is loaded every session, so only include things that apply broadly. For domain knowledge or workflows that are only relevant sometimes, use skills instead. Claude loads them on demand without bloating every conversation.Keep it concise. For each line, ask: “Would removing this cause Claude to make mistakes?” If not, cut it. Bloated CLAUDE.md files cause Claude to ignore your actual instructions!

如果 Claude 持续做出你不希望的行为,尽管有规则禁止,那可能是文件太长,规则被忽略了。如果 Claude 询问 CLAUDE.md 中已解答的问题,措辞可能含糊不清。将 CLAUDE.md 视为代码:在出现问题时审查它,定期修剪,并通过观察 Claude 的行为是否实际改变来测试更改。你可以通过添加强调(例如“重要”或“你必须”)来调整指令以提高遵从性。将 CLAUDE.md 提交到 git,以便你的团队可以贡献。该文件的价值会随时间累积。CLAUDE.md 文件可以使用 @path/to/import 语法导入其他文件:

If Claude keeps doing something you don’t want despite having a rule against it, the file is probably too long and the rule is getting lost. If Claude asks you questions that are answered in CLAUDE.md, the phrasing might be ambiguous. Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude’s behavior actually shifts.You can tune instructions by adding emphasis (e.g., “IMPORTANT” or “YOU MUST”) to improve adherence. Check CLAUDE.md into git so your team can contribute. The file compounds in value over time.CLAUDE.md files can import additional files using @path/to/import syntax:

参见 @README.md 获取项目概述,以及 @package.json 获取可用的 npm 命令。

See @README.md for project overview and @package.json for available npm commands.

附加说明 Additional Instructions

- Git 工作流:@docs/git-instructions.md

- Git workflow: @docs/git-instructions.md

- 个人覆盖:@~/.claude/my-project-instructions.md

- Personal overrides: @~/.claude/my-project-instructions.md

您可以将 CLAUDE.md 文件放置在多个位置:

You can place CLAUDE.md files in several locations:

* 主文件夹 (~/.claude/CLAUDE.md):适用于所有 Claude 会话

* Home folder (~/.claude/CLAUDE.md): applies to all Claude sessions

* 项目根目录 (./CLAUDE.md):提交到 git 以与团队共享

* Project root (./CLAUDE.md): check into git to share with your team

* 项目根目录 (./CLAUDE.local.md):个人项目特定笔记;将此文件添加到 .gitignore 中,以免与团队共享

* Project root (./CLAUDE.local.md): personal project-specific notes; add this file to your .gitignore so it isn’t shared with your team

* 父目录:适用于单仓库,其中 root/CLAUDE.md 和 root/foo/CLAUDE.md 会自动拉取

* Parent directories: useful for monorepos where both root/CLAUDE.md and root/foo/CLAUDE.md are pulled in automatically

* 子目录:当 Claude 读取子目录中的文件时,会按需拉取子目录中的 CLAUDE.md 文件

* Child directories: Claude pulls in child CLAUDE.md files on demand when it reads a file in those directories

配置权限 ​(https://www.anthropic.com/engineering/claude-code-best-practices#configure-permissions)

使用自动模式让分类器处理审批,/permissions 允许特定命令,或 /sandbox 进行操作系统级隔离。每种方式都能减少中断,同时让你保持控制。

Use auto mode to let a classifier handle approvals, /permissions to allowlist specific commands, or /sandbox for OS-level isolation. Each reduces interruptions while keeping you in control.

默认情况下,Claude Code 会请求对可能修改系统的操作进行权限确认:文件写入、Bash 命令、MCP 工具等。这很安全但很繁琐。在第十次批准后,你实际上不再审查,只是在点击通过。有三种方法可以减少这些中断:

By default, Claude Code requests permission for actions that might modify your system: file writes, Bash commands, MCP tools, etc. This is safe but tedious. After the tenth approval you’re not really reviewing anymore, you’re just clicking through. There are three ways to reduce these interruptions:

* 自动模式:一个独立的分类器模型审查命令,仅阻止看起来有风险的操作:权限升级、未知基础设施或恶意内容驱动的操作。当你信任任务的大方向但不想点击每一步时,此模式最佳。

* Auto mode: a separate classifier model reviews commands and blocks only what looks risky: scope escalation, unknown infrastructure, or hostile-content-driven actions. Best when you trust the general direction of a task but don’t want to click through every step

* 权限允许列表:允许你确信安全的特定工具,如 npm run lint 或 git commit。

* Permission allowlists: permit specific tools you know are safe, like npm run lint or git commit

* 沙箱:启用操作系统级隔离,限制文件系统和网络访问,让 Claude 在定义的边界内更自由地工作。

* Sandboxing: enable OS-level isolation that restricts filesystem and network access, allowing Claude to work more freely within defined boundaries

阅读更多关于权限模式、权限规则和沙箱的信息。

Read more about permission modes, permission rules, and sandboxing.

使用 CLI 工具 ​(https://www.anthropic.com/engineering/claude-code-best-practices#use-cli-tools)

告诉 Claude Code 在与外部服务交互时使用 CLI 工具,如 gh、aws、gcloud 和 sentry-cli。

Tell Claude Code to use CLI tools like gh, aws, gcloud, and sentry-cli when interacting with external services.

CLI 工具是与外部服务交互时上下文效率最高的方式。如果你使用 GitHub,请安装 gh CLI。Claude 知道如何使用它来创建问题、打开拉取请求和阅读评论。如果没有 gh,Claude 仍然可以使用 GitHub API,但未经身份验证的请求经常会遇到速率限制。Claude 也能有效学习它尚不熟悉的 CLI 工具。尝试使用类似“使用 'foo-cli-tool --help' 了解 foo 工具,然后用它解决 A、B、C”的提示。

CLI tools are the most context-efficient way to interact with external services. If you use GitHub, install the gh CLI. Claude knows how to use it for creating issues, opening pull requests, and reading comments. Without gh, Claude can still use the GitHub API, but unauthenticated requests often hit rate limits.Claude is also effective at learning CLI tools it doesn’t already know. Try prompts like Use 'foo-cli-tool --help' to learn about foo tool, then use it to solve A, B, C.

连接 MCP 服务器 ​(https://www.anthropic.com/engineering/claude-code-best-practices#connect-mcp-servers)

运行 claude mcp add 来连接外部工具,如 Notion、Figma 或你的数据库。

Run claude mcp add to connect external tools like Notion, Figma, or your database.

借助 MCP 服务器,你可以让 Claude 从问题跟踪器实现功能、查询数据库、分析监控数据、集成 Figma 的设计,并自动化工作流程。

With MCP servers, you can ask Claude to implement features from issue trackers, query databases, analyze monitoring data, integrate designs from Figma, and automate workflows.

设置钩子 ​(https://www.anthropic.com/engineering/claude-code-best-practices#set-up-hooks)

对于每次必须执行且零例外的情况,请使用钩子。

Use hooks for actions that must happen every time with zero exceptions.

钩子会在 Claude 工作流程的特定点自动运行脚本。与 CLAUDE.md 指令(仅提供建议)不同,钩子是确定性的,能保证动作执行。Claude 可以为您编写钩子。尝试使用诸如“编写一个钩子,在每次文件编辑后运行 eslint”或“编写一个阻止写入 migrations 文件夹的钩子”之类的提示。直接编辑.claude/settings.json 来手动配置钩子,并运行/hooks 来浏览已配置的内容。

Hooks run scripts automatically at specific points in Claude’s workflow. Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.Claude can write hooks for you. Try prompts like “Write a hook that runs eslint after every file edit” or “Write a hook that blocks writes to the migrations folder.” Edit .claude/settings.json directly to configure hooks by hand, and run /hooks to browse what’s configured.

创建技能 ​(https://www.anthropic.com/engineering/claude-code-best-practices#create-skills)

在 .claude/skills/ 中创建 SKILL.md 文件,为 Claude 提供领域知识和可复用的工作流程。

Create SKILL.md files in .claude/skills/ to give Claude domain knowledge and reusable workflows.

技能通过特定于你的项目、团队或领域的信息扩展 Claude 的知识。Claude 会在相关时自动应用它们,或者你可以直接使用 /skill-name 调用它们。通过向 .claude/skills/ 添加包含 SKILL.md 的目录来创建技能:

Skills extend Claude’s knowledge with information specific to your project, team, or domain. Claude applies them automatically when relevant, or you can invoke them directly with /skill-name.Create a skill by adding a directory with a SKILL.md to .claude/skills/:

description: 我们服务的 REST API 设计约定

description: REST API design conventions for our services

API 约定 API Conventions

- 始终为列表端点包含分页

- Always include pagination for list endpoints

- 在 URL 路径中标注 API 版本(/v1/、/v2/)

- Version APIs in the URL path (/v1/, /v2/)

技能还可以定义您直接调用的可重复工作流:

Skills can also define repeatable workflows you invoke directly:

分析并修复 GitHub 问题:$ARGUMENTS。

Analyze and fix the GitHub issue: $ARGUMENTS.

1. 使用 gh issue view 获取问题详情

1. Use gh issue view to get the issue details

2. 理解问题中描述的问题

2. Understand the problem described in the issue

3. 在代码库中搜索相关文件

3. Search the codebase for relevant files

4. 实施必要的更改以修复问题

4. Implement the necessary changes to fix the issue

6. 确保代码通过 lint 和类型检查

6. Ensure code passes linting and type checking

运行 /fix-issue 1234 来调用它。对于具有副作用且您希望手动触发的工作流,请使用 disable-model-invocation: true。

Run /fix-issue 1234 to invoke it. Use disable-model-invocation: true for workflows with side effects that you want to trigger manually.

创建自定义子智能体 ​(https://www.anthropic.com/engineering/claude-code-best-practices#create-custom-subagents)

在 .claude/agents/ 中定义专门的助手,Claude 可以委托它们执行隔离的任务。

Define specialized assistants in .claude/agents/ that Claude can delegate to for isolated tasks.

子智能体在自己的上下文中运行,拥有自己允许的工具集。它们适用于读取许多文件或需要专门关注而不干扰主对话的任务。

Subagents run in their own context with their own set of allowed tools. They’re useful for tasks that read many files or need specialized focus without cluttering your main conversation.

description: 审查代码中的安全漏洞

description: Reviews code for security vulnerabilities

你是一名高级安全工程师。审查代码中的:

You are a senior security engineer. Review code for:

- 注入漏洞(SQL、XSS、命令注入)

- Injection vulnerabilities (SQL, XSS, command injection)

提供具体的行引用和建议的修复。

Provide specific line references and suggested fixes.

明确告诉 Claude 使用子智能体:“使用子智能体审查此代码的安全问题。”

Tell Claude to use subagents explicitly: “Use a subagent to review this code for security issues.”

安装插件 ​(https://www.anthropic.com/engineering/claude-code-best-practices#install-plugins)

运行 /plugin 浏览市场。插件无需配置即可添加技能、工具和集成。

Run /plugin to browse the marketplace. Plugins add skills, tools, and integrations without configuration.

插件将技能、钩子、子智能体和 MCP 服务器打包成一个可安装单元,来自社区和 Anthropic。如果你使用类型化语言,安装代码智能插件,让 Claude 获得精确的符号导航和编辑后的自动错误检测。关于选择技能、子智能体、钩子和 MCP 的指导,请参阅扩展 Claude Code。

Plugins bundle skills, hooks, subagents, and MCP servers into a single installable unit from the community and Anthropic. If you work with a typed language, install a code intelligence plugin to give Claude precise symbol navigation and automatic error detection after edits.For guidance on choosing between skills, subagents, hooks, and MCP, see Extend Claude Code.

有效沟通 ​(https://www.anthropic.com/engineering/claude-code-best-practices#communicate-effectively)

与 Claude Code 的沟通方式会显著影响结果质量。

The way you communicate with Claude Code significantly impacts the quality of results.

代码库问答 ​(https://www.anthropic.com/engineering/claude-code-best-practices#ask-codebase-questions)

向 Claude 提出你会问资深工程师的问题。

Ask Claude questions you’d ask a senior engineer.

在接手新代码库时,使用 Claude Code 进行学习和探索。你可以向 Claude 提出你会问其他工程师的同类问题:

When onboarding to a new codebase, use Claude Code for learning and exploration. You can ask Claude the same sorts of questions you would ask another engineer:

* foo.rs 第 134 行的 async move { ... } 是做什么的?

* What does async move { ... } do on line 134 of foo.rs?

* CustomerOnboardingFlowImpl 处理了哪些边界情况?

* What edge cases does CustomerOnboardingFlowImpl handle?

* 为什么第 333 行的代码调用 foo() 而不是 bar()?

* Why does this code call foo() instead of bar() on line 333?

以这种方式使用 Claude Code 是一种有效的入职工作流程,可以加快上手速度并减轻其他工程师的负担。无需特殊提示:直接提问即可。

Using Claude Code this way is an effective onboarding workflow, improving ramp-up time and reducing load on other engineers. No special prompting required: ask questions directly.

让 Claude 先对你进行访谈 ​(https://www.anthropic.com/engineering/claude-code-best-practices#let-claude-interview-you)

对于较大的功能,先让 Claude 对你进行访谈。从一个极简的提示开始,让 Claude 使用 AskUserQuestion 工具对你进行访谈。

For larger features, have Claude interview you first. Start with a minimal prompt and ask Claude to interview you using the AskUserQuestion tool.

Claude 会询问你可能尚未考虑的事项,包括技术实现、UI/UX、边界情况和权衡。

Claude asks about things you might not have considered yet, including technical implementation, UI/UX, edge cases, and tradeoffs.

我想构建[简要描述]。使用 AskUserQuestion 工具对我进行详细访谈。

I want to build [brief description]. Interview me in detail using the AskUserQuestion tool.

询问技术实现、UI/UX、边界情况、关注点和权衡。不要问显而易见的问题,深入挖掘我可能未考虑的难点。

Ask about technical implementation, UI/UX, edge cases, concerns, and tradeoffs. Don't ask obvious questions, dig into the hard parts I might not have considered.

持续访谈直到我们覆盖所有内容,然后编写完整的规范到 SPEC.md。

Keep interviewing until we've covered everything, then write a complete spec to SPEC.md.

一旦规范完成,启动一个新的会话去执行它。新会话拥有完全专注于实现的干净上下文,并且你有一个书面的规范可供参考。最有用的规范是自包含的:它们命名了涉及的文件和接口,说明了哪些内容不在范围内,并以一个端到端的验证步骤结束,证明该功能有效。花在使规范精确上的时间比花在观察实现上的时间更有价值。

Once the spec is complete, start a fresh session to execute it. The new session has clean context focused entirely on implementation, and you have a written spec to reference.The most useful specs are self-contained: they name the files and interfaces involved, state what is out of scope, and end with an end-to-end verification step that proves the feature works. Time spent making the spec precise pays off more than time spent watching the implementation.

管理会话 ​(https://www.anthropic.com/engineering/claude-code-best-practices#manage-your-session)

对话是持久且可逆的。善加利用这一点!

Conversations are persistent and reversible. Use this to your advantage!

及早并频繁纠偏 ​(https://www.anthropic.com/engineering/claude-code-best-practices#course-correct-early-and-often)

一旦发现 Claude 偏离轨道,立即纠正。

Correct Claude as soon as you notice it going off track.

最佳结果来自紧密的反馈循环。虽然 Claude 偶尔能一次完美解决问题,但快速纠正通常能更快产生更好的解决方案。

The best results come from tight feedback loops. Though Claude occasionally solves problems perfectly on the first attempt, correcting it quickly generally produces better solutions faster.

* Esc:按 Esc 键中途停止 Claude 的操作。上下文得以保留,因此你可以重新引导。

* Esc: stop Claude mid-action with the Esc key. Context is preserved, so you can redirect.

* Esc + Esc 或 /rewind:按两次 Esc 或运行/rewind 打开回退菜单,恢复之前的对话和代码状态,或从选中的消息进行总结。

* Esc + Esc or /rewind: press Esc twice or run /rewind to open the rewind menu and restore previous conversation and code state, or summarize from a selected message.

* "撤销":让 Claude 撤销其更改。

* "Undo that": have Claude revert its changes.

* /clear:在不相关的任务之间重置上下文。包含无关上下文的长时间会话会降低性能。

* /clear: reset context between unrelated tasks. Long sessions with irrelevant context can reduce performance.

如果在一次会话中你已就同一问题纠正 Claude 超过两次,则上下文中充斥着失败的尝试。运行/clear,并根据你学到的经验,用更具体的提示重新开始。一个干净会话加上更好的提示,几乎总是优于积累了多次纠正的长会话。

If you’ve corrected Claude more than twice on the same issue in one session, the context is cluttered with failed approaches. Run /clear and start fresh with a more specific prompt that incorporates what you learned. A clean session with a better prompt almost always outperforms a long session with accumulated corrections.

积极管理上下文 ​(https://www.anthropic.com/engineering/claude-code-best-practices#manage-context-aggressively)

在不相关的任务之间运行 /clear 以重置上下文。

Run /clear between unrelated tasks to reset context.

当接近上下文限制时,Claude Code 会自动压缩对话历史,这能在释放空间的同时保留重要的代码和决策。在长时间会话中,Claude 的上下文窗口可能会被无关的对话、文件内容和命令填满,这会降低性能,有时还会分散 Claude 的注意力。

Claude Code automatically compacts conversation history when you approach context limits, which preserves important code and decisions while freeing space.During long sessions, Claude’s context window can fill with irrelevant conversation, file contents, and commands. This can reduce performance and sometimes distract Claude.

* 在任务之间频繁使用 /clear 以完全重置上下文窗口

* Use /clear frequently between tasks to reset the context window entirely

* 当自动压缩触发时,Claude 会总结最重要的内容,包括代码模式、文件状态和关键决策

* When auto compaction triggers, Claude summarizes what matters most, including code patterns, file states, and key decisions

* 如需更多控制,运行 /compact <指令>,例如 /compact 专注于 API 变更

* For more control, run /compact <instructions>, like /compact Focus on the API changes

* 要仅压缩部分对话,使用 Esc + Esc 或 /rewind,选择一个消息检查点,然后选择“从此处总结”或“总结到此为止”。前者会压缩从该点开始的消息,同时保持早期上下文完整;后者会压缩早期消息,同时完整保留最近的消息。参见“恢复与总结”。

* To compact only part of the conversation, use Esc + Esc or /rewind, select a message checkpoint, and choose Summarize from here or Summarize up to here. The first condenses messages from that point forward while keeping earlier context intact; the second condenses earlier messages while keeping recent ones in full. See Restore vs. summarize.

* 在 CLAUDE.md 中自定义压缩行为,例如使用指令“压缩时,始终保留修改文件的完整列表和任何测试命令”,以确保关键上下文在总结后得以保留

* Customize compaction behavior in CLAUDE.md with instructions like "When compacting, always preserve the full list of modified files and any test commands" to ensure critical context survives summarization

* 对于不需要保留在上下文中的快速问题,使用 /btw。答案会出现在一个可关闭的覆盖层中,且永远不会进入对话历史,因此你可以在不增加上下文的情况下检查细节。

* For quick questions that don’t need to stay in context, use /btw. The answer appears in a dismissible overlay and never enters conversation history, so you can check a detail without growing context.

使用子智能体进行调查 ​(https://www.anthropic.com/engineering/claude-code-best-practices#use-subagents-for-investigation)

使用“use subagents to investigate X”来委托研究。它们在单独的上下文中探索,保持主对话的整洁以便实现。

Delegate research with "use subagents to investigate X". They explore in a separate context, keeping your main conversation clean for implementation.

由于上下文是您的基本约束,子智能体是可用的最强大工具之一。当 Claude 研究代码库时,它会读取大量文件,这些文件都会消耗您的上下文。子智能体在单独的上下文窗口中运行,并报告摘要:

Since context is your fundamental constraint, subagents are one of the most powerful tools available. When Claude researches a codebase it reads lots of files, all of which consume your context. Subagents run in separate context windows and report back summaries:

使用子智能体调查我们的认证系统如何处理令牌刷新,以及我们是否有任何现有的 OAuth 工具可以重用。

Use subagents to investigate how our authentication system handles token

子智能体探索代码库,读取相关文件,并报告发现,所有这些都不会使您的主对话变得杂乱。您也可以在 Claude 实现某些内容后使用子智能体进行验证:

refresh, and whether we have any existing OAuth utilities I should reuse.

使用子智能体审查此代码的边缘情况

The subagent explores the codebase, reads relevant files, and reports back with findings, all without cluttering your main conversation.You can also use subagents for verification after Claude implements something:

use a subagent to review this code for edge cases

回退与检查点 ​(https://www.anthropic.com/engineering/claude-code-best-practices#rewind-with-checkpoints)

你发送的每个提示都会创建一个检查点。你可以将对话、代码或两者恢复到之前的任何检查点。

Every prompt you send creates a checkpoint. You can restore conversation, code, or both to any previous checkpoint.

Claude 会在每次更改前自动快照文件,以便检查点可以恢复它们。双击 Escape 或运行 /rewind 打开回退菜单。你可以仅恢复对话、仅恢复代码、恢复两者,或从选中的消息进行总结。详情请参见检查点。无需仔细规划每一步,你可以让 Claude 尝试一些有风险的操作。如果不起作用,回退并尝试不同的方法。检查点跨会话持久化,因此你可以关闭终端,稍后仍可回退。

Claude automatically snapshots files before each change so a checkpoint can restore them. Double-tap Escape or run /rewind to open the rewind menu. You can restore conversation only, restore code only, restore both, or summarize from a selected message. See Checkpointing for details.Instead of carefully planning every move, you can tell Claude to try something risky. If it doesn’t work, rewind and try a different approach. Checkpoints persist across sessions, so you can close your terminal and still rewind later.

检查点仅跟踪由 Claude 所做的更改,而非外部进程。这不能替代 git。

Checkpoints only track changes made by Claude, not external processes. This isn’t a replacement for git.

恢复对话 ​(https://www.anthropic.com/engineering/claude-code-best-practices#resume-conversations)

使用 /rename 为会话命名,并将其视为分支:每个工作流都有自己持久的上下文。

Name sessions with /rename and treat them like branches: each workstream gets its own persistent context.

Claude Code 在本地保存对话,因此当任务跨越多次工作时,您无需重新解释上下文。运行 claude --continue 以继续最近的会话,或运行 claude --resume 从列表中选择。为会话赋予描述性名称,如 oauth-migration,以便日后查找。有关恢复、分支和命名控制的完整说明,请参阅管理会话。

Claude Code saves conversations locally, so when a task spans multiple sittings you don’t have to re-explain the context. Run claude --continue to pick up the most recent session, or claude --resume to choose from a list. Give sessions descriptive names like oauth-migration so you can find them later. See Manage sessions for the full set of resume, branch, and naming controls.

自动化与规模化 ​(https://www.anthropic.com/engineering/claude-code-best-practices#automate-and-scale)

一旦你熟练使用单个 Claude,就可以通过并行会话、非交互模式和扇出模式来成倍提升产出。到目前为止,所有内容都假设一个人、一个 Claude 和一次对话。但 Claude Code 支持水平扩展。本节中的技巧将展示如何完成更多工作。

Once you’re effective with one Claude, multiply your output with parallel sessions, non-interactive mode, and fan-out patterns.Everything so far assumes one human, one Claude, and one conversation. But Claude Code scales horizontally. The techniques in this section show how you can get more done.

非交互模式运行 ​(https://www.anthropic.com/engineering/claude-code-best-practices#run-non-interactive-mode)

在 CI、pre-commit 钩子或脚本中使用 `claude -p "prompt"`。添加 `--output-format stream-json --verbose` 以获取流式 JSON 输出。

Use claude -p "prompt" in CI, pre-commit hooks, or scripts. Add --output-format stream-json --verbose for streaming JSON output.

通过 `claude -p "your prompt"`,你可以非交互式地运行 Claude,无需会话。非交互模式是将 Claude 集成到 CI 流水线、pre-commit 钩子或任何自动化工作流中的方式。输出格式允许你以编程方式解析结果:纯文本、JSON 或流式 JSON。

With claude -p "your prompt", you can run Claude non-interactively, without a session. Non-interactive mode is how you integrate Claude into CI pipelines, pre-commit hooks, or any automated workflow. The output formats let you parse results programmatically: plain text, JSON, or streaming JSON.

一次性查询 One-off queries

claude -p "解释这个项目的作用"

claude -p "Explain what this project does"

脚本的结构化输出 Structured output for scripts

claude -p "列出所有 API 端点" --output-format json

claude -p "List all API endpoints" --output-format json

实时处理的流式传输 Streaming for real-time processing

claude -p "分析此日志文件" --output-format stream-json --verbose

claude -p "Analyze this log file" --output-format stream-json --verbose

并行运行多个 Claude 会话 ​(https://www.anthropic.com/engineering/claude-code-best-practices#run-multiple-claude-sessions)

并行运行多个 Claude 会话以加速开发、运行隔离实验或启动复杂工作流。

Run multiple Claude sessions in parallel to speed up development, run isolated experiments, or start complex workflows.

选择适合您所需协调程度的并行方式:

Pick the parallel approach that fits how much coordination you want to do yourself:

* 工作树:在隔离的 git 检出中运行单独的 CLI 会话,避免编辑冲突

* Worktrees: run separate CLI sessions in isolated git checkouts so edits don’t collide

* 桌面应用:在各自的工作树中可视化管理多个本地会话

* Desktop app: manage multiple local sessions visually, each in its own worktree

* 网页版 Claude Code:在 Anthropic 管理的云基础设施上的隔离虚拟机中运行会话

* Claude Code on the web: run sessions on Anthropic-managed cloud infrastructure in isolated VMs

* 智能体团队:通过共享任务、消息传递和团队领导自动协调多个会话

* Agent teams: automated coordination of multiple sessions with shared tasks, messaging, and a team lead

除了并行化工作,多个会话还能实现注重质量的工作流。新的上下文能改善代码审查,因为 Claude 不会对自己刚写的代码产生偏见。例如,使用编写者/审查者模式:

Beyond parallelizing work, multiple sessions enable quality-focused workflows. A fresh context improves code review since Claude won’t be biased toward code it just wrote.For example, use a Writer/Reviewer pattern:

您也可以对测试做类似的事情:让一个 Claude 编写测试,然后让另一个 Claude 编写代码通过测试。

You can do something similar with tests: have one Claude write tests, then another write code to pass them.

跨文件扇出 ​(https://www.anthropic.com/engineering/claude-code-best-practices#fan-out-across-files)

循环遍历任务,对每个任务调用 claude -p。使用 --allowedTools 来限定批处理操作的权限范围。

Loop through tasks calling claude -p for each. Use --allowedTools to scope permissions for batch operations.

对于大型迁移或分析,你可以将工作分布到多个并行的 Claude 调用中:

For large migrations or analyses, you can distribute work across many parallel Claude invocations:

让 Claude 列出所有需要迁移的文件(例如,列出所有需要迁移的 2,000 个 Python 文件)

Have Claude list all files that need migrating (e.g., list all 2,000 Python files that need migrating)

claude -p "将 $file 从 React 迁移到 Vue。返回 OK 或 FAIL。" \

claude -p "Migrate $file from React to Vue. Return OK or FAIL." \

根据前 2-3 个文件出现的问题优化你的提示词,然后对整个集合运行。--allowedTools 标志限制了 Claude 能做什么,这在无人值守运行时很重要。

Refine your prompt based on what goes wrong with the first 2-3 files, then run on the full set. The --allowedTools flag restricts what Claude can do, which matters when you’re running unattended.

你也可以将 Claude 集成到现有的数据处理/处理管道中:

You can also integrate Claude into existing data/processing pipelines:

claude -p "<你的提示词>" --output-format json | your_command

claude -p "<your prompt>" --output-format json | your_command

在开发期间使用 --verbose 进行调试,在生产环境中关闭它。

Use --verbose for debugging during development, and turn it off in production.

自动模式 ​(https://www.anthropic.com/engineering/claude-code-best-practices#run-autonomously-with-auto-mode)

如需在后台安全检查下不间断执行,请使用自动模式。分类器模型会在命令运行前对其进行审查,阻止权限升级、未知基础设施以及恶意内容驱动的操作,同时允许常规工作无需提示即可进行。

For uninterrupted execution with background safety checks, use auto mode. A classifier model reviews commands before they run, blocking scope escalation, unknown infrastructure, and hostile-content-driven actions while letting routine work proceed without prompts.

claude --permission-mode auto -p "修复所有 lint 错误"

claude --permission-mode auto -p "fix all lint errors"

对于使用 -p 标志的非交互式运行,如果分类器反复阻止操作,自动模式将中止,因为没有用户可回退。请参阅自动模式回退的阈值。

For non-interactive runs with the -p flag, auto mode aborts if the classifier repeatedly blocks actions, since there is no user to fall back to. See when auto mode falls back for thresholds.

添加对抗性审查步骤 ​(https://www.anthropic.com/engineering/claude-code-best-practices#add-an-adversarial-review-step)

在将任务视为完成之前,让一个子智能体在新的上下文中审查差异并报告差距。

Before treating a task as done, have a subagent review the diff in a fresh context and report gaps.

Claude 无人值守工作的时间越长,在将工作视为完成之前,独立检查就越重要。在新子智能体上下文中运行的审查者只看到差异和您给出的标准,而不是产生更改的推理过程,因此它会根据自己的标准评估结果。对于正确性检查,运行捆绑的 /code-review 技能,该技能会在新的子智能体中审查当前差异中的错误,并将结果返回给会话。要对照您的计划检查差异,请自行编写审查提示。指定要检查的工作、要对照的计划以及什么算作发现:

The longer Claude works unattended, the more an independent check matters before you count the work as done. A reviewer running in a fresh subagent context sees only the diff and the criteria you give it, not the reasoning that produced the change, so it evaluates the result on its own terms.For a correctness check, run the bundled /code-review skill, which reviews the current diff for bugs in a fresh subagent and returns findings to the session. To check the diff against your plan instead, write the review prompt yourself. Name the work to check, the plan to check it against, and what counts as a finding:

使用子智能体对照 PLAN.md 审查速率限制器差异。检查是否每个需求都已实现,列出的边缘情况是否有测试,以及任务范围之外的内容是否未更改。报告差距,而不是风格偏好。

Use a subagent to review the rate limiter diff against PLAN.md. Check that

由于审查者作为子智能体运行,实现会话会直接收到差距,并可以在不复制发现的情况下修复和重新审查。对于更长的自主运行,智能体团队可以在许多任务中保持此循环,而您则抽查记录的发现。

every requirement is implemented, the listed edge cases have tests, and

被提示要发现差距的审查者通常会报告一些差距,即使工作本身是合理的,因为这是它被要求做的。追逐每一个发现会导致过度工程:额外的抽象层、防御性代码以及针对不可能发生的情况的测试。告诉审查者只标记影响正确性或规定要求的差距,并将其余部分视为可选的。

nothing outside the task's scope changed. Report gaps, not style preferences.

Because the reviewer runs as a subagent, the implementing session receives the gaps directly and can fix them and re-review without you copying findings between windows. For longer autonomous runs, an agent team can keep this loop going across many tasks while you spot-check the recorded findings.

A reviewer prompted to find gaps will usually report some, even when the work is sound, because that is what it was asked to do. Chasing every finding leads to over-engineering: extra abstraction layers, defensive code, and tests for cases that can’t happen. Tell the reviewer to flag only gaps that affect correctness or the stated requirements, and treat the rest as optional.

避免常见失败模式 ​(https://www.anthropic.com/engineering/claude-code-best-practices#avoid-common-failure-patterns)

这些是常见错误。及早识别它们可以节省时间:

These are common mistakes. Recognizing them early saves time:

* 厨房水槽式会话。你从一个任务开始,然后问 Claude 一些无关的事情,再回到第一个任务。上下文中充满了不相关的信息。

* The kitchen sink session. You start with one task, then ask Claude something unrelated, then go back to the first task. Context is full of irrelevant information.

* 反复纠正。Claude 做错了,你纠正它,它仍然错误,你再次纠正。上下文中充满了失败的尝试。

* Correcting over and over. Claude does something wrong, you correct it, it’s still wrong, you correct again. Context is polluted with failed approaches.

* 过度指定的 CLAUDE.md。如果你的 CLAUDE.md 太长,Claude 会忽略其中一半内容,因为重要规则在噪声中丢失。

* The over-specified CLAUDE.md. If your CLAUDE.md is too long, Claude ignores half of it because important rules get lost in the noise.

* 信任然后验证的差距。Claude 生成了一个看似合理的实现,但没有处理边界情况。

* The trust-then-verify gap. Claude produces a plausible-looking implementation that doesn’t handle edge cases.

* 无限探索。你让 Claude“调查”某事而没有限定范围。Claude 读取了数百个文件,填满了上下文。

* The infinite exploration. You ask Claude to “investigate” something without scoping it. Claude reads hundreds of files, filling the context.

培养直觉 ​(https://www.anthropic.com/engineering/claude-code-best-practices#develop-your-intuition)

本指南中的模式并非一成不变。它们是在一般情况下效果不错的起点,但可能并非对所有情况都最优。有时你_应该_让上下文累积,因为你正深入一个复杂问题,历史信息很有价值。有时你应该跳过规划,让 Claude 自己解决,因为任务是探索性的。有时模糊的提示恰恰合适,因为你希望在约束之前看看 Claude 如何理解问题。注意什么有效。当 Claude 产生出色输出时,留意你做了什么:提示结构、提供的上下文、使用的模式。当 Claude 遇到困难时,问为什么。是上下文太嘈杂?提示太模糊?任务太大一次完成不了?随着时间的推移,你会培养出任何指南都无法捕捉的直觉。你会知道何时具体、何时开放,何时规划、何时探索,何时清除上下文、何时让它累积。

The patterns in this guide aren’t set in stone. They’re starting points that work well in general, but might not be optimal for every situation.Sometimes you should let context accumulate because you’re deep in one complex problem and the history is valuable. Sometimes you should skip planning and let Claude figure it out because the task is exploratory. Sometimes a vague prompt is exactly right because you want to see how Claude interprets the problem before constraining it.Pay attention to what works. When Claude produces great output, notice what you did: the prompt structure, the context you provided, the mode you were in. When Claude struggles, ask why. Was the context too noisy? The prompt too vague? The task too big for one pass?Over time, you’ll develop intuition that no guide can capture. You’ll know when to be specific and when to be open-ended, when to plan and when to explore, when to clear context and when to let it accumulate.

相关资源 ​(https://www.anthropic.com/engineering/claude-code-best-practices#related-resources)

* Claude Code 的工作原理:智能体循环、工具和上下文管理

* How Claude Code works: the agentic loop, tools, and context management

* 扩展 Claude Code:技能、钩子、MCP、子智能体和插件

* Extend Claude Code: skills, hooks, MCP, subagents, and plugins

* 常见工作流:调试、测试、PR 等的分步指南

* Common workflows: step-by-step recipes for debugging, testing, PRs, and more

* CLAUDE.md:存储项目约定和持久化上下文

* CLAUDE.md: store project conventions and persistent context

Anthropic 招聘 经济未来 研究 新闻 信任中心 透明度

AnthropicCareersEconomic FuturesResearchNewsTrust centerTransparency

课程 MCP 连接器 客户案例 工程博客 活动 由 Claude 提供支持 服务合作伙伴 初创企业计划

CoursesMCP connectorsCustomer storiesEngineering blogEventsPowered by ClaudeService partnersStartups program

隐私选择 隐私政策 披露政策 使用政策 商业条款 消费者条款

Privacy choicesPrivacy policyDisclosure policyUsage policyCommercial termsConsumer terms

回复由 AI 生成,可能包含错误。

Responses are generated using AI and may contain mistakes.

互动版:图/公式 + 针对本篇提问 →