A practical guide for using CLAUDE.md files to optimize your use of Claude Code.

  • Category
  • Product
    Claude Code
  • Date
    November 25, 2025
  • Reading time
    5
    min
  • Share
    Copy link
    https://claude.com/blog/using-claude-md-files

If you use AI coding agents, you face the same challenge: how do you give them enough context to understand your architecture, conventions, and workflows without repeating yourself?如果你使用AI编码代理,你会面临同样的挑战:如何在不重复自己的情况下,给它们足够的上下文来理解你的架构、约定和工作流程?

The problem compounds as your codebase grows. Complex module relationships, domain-specific patterns, and team conventions don't surface easily. You end up explaining the same architectural decisions, testing requirements, and code style preferences at the start of every conversation.随着代码库的增长,问题会加剧。复杂的模块关系、领域特定模式和团队约定不易显现。你最终不得不在每次对话开始时解释相同的架构决策、测试要求和代码风格偏好。

CLAUDE.md files solve this by giving Claude persistent context about your project. Think of it as a configuration file that Claude automatically incorporates into every conversation, ensuring it always knows your project structure, coding standards, and preferred workflows.CLAUDE.md文件通过为Claude提供关于项目的持久上下文来解决这个问题。可以把它看作一个配置文件,Claude会自动将其纳入每次对话,确保它始终了解你的项目结构、编码标准和首选工作流程。

In this article, we walk through how to structure your CLAUDE.md, share best practices, and tips for using them to get the most out of Claude Code. 在本文中,我们将介绍如何构建你的CLAUDE.md,分享最佳实践,以及使用它们来充分利用Claude Code的技巧。

What is a CLAUDE.md file?什么是CLAUDE.md文件?

CLAUDE.md is a special configuration file that lives in your repository and provides Claude with project-specific context. You can place it in your repository root to share with your team, in parent directories for monorepo setups, or in your home folder for universal application across all projects.CLAUDE.md是一个特殊的配置文件,位于你的仓库中,为Claude提供项目特定的上下文。你可以将其放在仓库根目录与团队共享,放在父目录用于单体仓库设置,或放在主文件夹中以便在所有项目中通用。

Here’s an example CLAUDE.md that you might have in your repository:以下是一个你可能在仓库中拥有的CLAUDE.md示例:

# Project Context

When working with this codebase, prioritize readability over cleverness. Ask clarifying questions before making architectural changes.

## About This Project

FastAPI REST API for user authentication and profiles. Uses SQLAlchemy for database operations and Pydantic for validation.

## Key Directories

- `app/models/` - database models
- `app/api/` - route handlers
- `app/core/` - configuration and utilities

## Standards

- Type hints required on all functions
- pytest for testing (fixtures in `tests/conftest.py`)
- PEP 8 with 100 character lines

## Common Commands
```bash
uvicorn app.main:app --reload  # dev server
pytest tests/ -v               # run tests
```

## Notes

All routes use `/api/v1` prefix. JWT tokens expire after 24 hours.

A well-configured CLAUDE.md transforms how Claude works with your specific project. The file serves multiple purposes: providing architectural context, establishing workflows, and connecting Claude to your development tools. Each addition should solve a real problem you have encountered, not theoretical concerns about what Claude might need.一个配置良好的CLAUDE.md会改变Claude与你特定项目协作的方式。该文件有多个用途:提供架构上下文、建立工作流程、将Claude连接到你的开发工具。每个添加的内容都应解决你遇到的实际问题,而不是关于Claude可能需要的理论担忧。

This file can document common bash commands, core utilities, code style guidelines, testing instructions, repository conventions, developer environment setup, and project-specific warnings. There is no required format. The recommendation is to keep this file concise and human-readable, treating it like documentation that both humans and Claude need to understand quickly.该文件可以记录常见的bash命令、核心工具、代码风格指南、测试说明、仓库约定、开发者环境设置以及项目特定的警告。没有固定的格式。建议保持文件简洁且人类可读,将其视为人类和Claude都需要快速理解的文档。

Your CLAUDE.md file becomes part of Claude's system prompt. Every conversation starts with this context already loaded, eliminating the need to explain basic project information repeatedly.你的CLAUDE.md文件会成为Claude系统提示的一部分。每次对话都会从已加载的上下文开始,无需重复解释基本项目信息。

Getting started with /init使用/init入门

Creating a CLAUDE.md from scratch can feel daunting, especially in an unfamiliar codebase. 从头创建CLAUDE.md可能令人望而生畏,尤其是在不熟悉的代码库中。

The /init command automates this process by analyzing your project and generating a starter configuration./init命令通过分析你的项目并生成一个起始配置来自动化这个过程。

Run /init in any Claude Code session:在任何Claude Code会话中运行/init:

cd your-project
claude
/init

Claude examines your codebase—reading package files, existing documentation, configuration files, and code structure—then generates a CLAUDE.md tailored to your project. The generated file typically includes build commands, test instructions, key directories, and coding conventions it detected.Claude会检查你的代码库——读取包文件、现有文档、配置文件和代码结构——然后生成一个针对你项目定制的CLAUDE.md。生成的文件通常包括构建命令、测试说明、关键目录以及它检测到的编码约定。

Think of /init as a starting point, not a finished product. The generated CLAUDE.md captures obvious patterns but may miss nuances specific to your workflow. Review what Claude produces and refine it based on your team's actual practices.将/init视为起点,而非成品。生成的CLAUDE.md捕捉了明显的模式,但可能遗漏了你工作流程中的细微差别。审查Claude生成的内容,并根据团队的实际实践进行优化。

You can also use /init on existing projects that already have a CLAUDE.md. Claude will review the current file and suggest improvements based on what it learns from exploring your codebase.你也可以在已有CLAUDE.md的现有项目上使用/init。Claude会审查当前文件,并根据从探索代码库中学到的内容提出改进建议。

After running /init, consider these next steps:运行/init后,考虑以下后续步骤:

  • Review the generated content for accuracy审查生成内容的准确性
  • Add workflow instructions Claude couldn't infer (branch naming conventions, deployment processes, code review requirements)添加Claude无法推断的工作流程说明(分支命名约定、部署流程、代码审查要求)
  • Remove generic guidance that doesn't apply to your project删除不适用于你项目的通用指导
  • Commit the file to version control so your team benefits将文件提交到版本控制,以便你的团队受益

The /init command works well for getting oriented quickly, but the real value comes from iterating on the generated file over time. As you work with Claude Code, use the # key to add instructions you find yourself repeating—these additions accumulate into a CLAUDE.md that genuinely reflects how your team works./init命令对于快速入门很有效,但真正的价值在于随着时间的推移迭代生成的文件。当你使用Claude Code时,使用#键添加你发现自己重复的指令——这些积累会形成一个真正反映团队工作方式的CLAUDE.md。

How to structure your CLAUDE.md如何构建你的CLAUDE.md

The following sections show you how to structure content for maximum impact: navigating complex architectures, tracking progress on multi-step tasks, integrating custom tools, and preventing rework through consistent workflows.以下部分将向你展示如何构建内容以获得最大影响:导航复杂架构、跟踪多步骤任务的进度、集成自定义工具以及通过一致的工作流程防止返工。

Give Claude a map给Claude一张地图

Explaining your project architecture, key libraries, and coding styles becomes tedious when you do it for every new task. You need Claude to maintain consistent context about your codebase structure without manual reinforcement.为每个新任务解释你的项目架构、关键库和编码风格变得繁琐。你需要Claude在无需手动强化的情况下,保持对代码库结构的一致上下文。

Add a project summary and high-level directory structure to your CLAUDE.md. This gives Claude immediate orientation when navigating your codebase. 在CLAUDE.md中添加项目摘要和高级目录结构。这能让Claude在导航代码库时立即获得方向感。

A simple tree output showing key directories helps Claude understand where different components live:一个显示关键目录的简单树状输出有助于Claude理解不同组件的位置:

main.py
├── logs
│   ├── application.log
├── modules
│   ├── cli.py
│   ├── logging_utils.py
│   ├── media_handler.py
│   ├── player.py

Include information about your main dependencies, architectural patterns, and any non-standard organizational choices. If you use domain-driven design, microservices, or specific frameworks, document that. Claude uses this map to make better decisions about where to find code and where to make changes.包含关于主要依赖项、架构模式以及任何非标准组织选择的信息。如果你使用领域驱动设计、微服务或特定框架,请记录下来。Claude使用这张地图来更好地决定在哪里查找代码以及在哪里进行更改。

Connect Claude to your tools将Claude连接到你的工具

Claude inherits your complete environment but needs guidance on which custom tools and scripts to use. Your team likely has specialized utilities for deployment, testing, or code generation that Claude should know about.Claude继承你的完整环境,但需要指导哪些自定义工具和脚本可以使用。你的团队可能拥有Claude应该了解的用于部署、测试或代码生成的专门工具。

Document your custom tools in CLAUDE.md with usage examples. Include tool names, basic usage patterns, and when to invoke them. If your tool provides help documentation through a --help flag, mention that so Claude knows to check it. For complex tools, add examples of common invocations your team uses regularly.在CLAUDE.md中记录你的自定义工具,并附上使用示例。包括工具名称、基本使用模式以及何时调用它们。如果你的工具通过--help标志提供帮助文档,请提及这一点,以便Claude知道去查看。对于复杂工具,添加团队经常使用的常见调用示例。

Claude functions as an MCP (Model Context Protocol) client, connecting to MCP servers that extend its capabilities. Configure these through project settings, global configuration, or checked-in .mcp.json files. The --mcp-debug flag helps troubleshoot connection issues when tools don't appear as expected.Claude作为MCP(模型上下文协议)客户端运行,连接到扩展其能力的MCP服务器。通过项目设置、全局配置或已检入的.mcp.json文件来配置这些。--mcp-debug标志有助于在工具未按预期出现时排查连接问题。

For example, if you have a Slack MCP server configured for your organization and you need Claude to understand how to use it, include something like this in CLAUDE.md:例如,如果你为组织配置了Slack MCP服务器,并且需要Claude理解如何使用它,请在CLAUDE.md中包含类似以下内容:

### Slack MCP
- Posts to #dev-notifications channel only
- Use for deployment notifications and build failures
- Do not use for individual PR updates (those go through GitHub webhooks)
- Rate limited to 10 messages per hour

Learn more about MCP fundamentals and best practices.了解更多关于MCP基础知识和最佳实践的信息。

For more information on setting permissions for Claude Code, see settings.json documentation at code.claude.com.有关为Claude Code设置权限的更多信息,请参阅code.claude.com上的settings.json文档。

Define standard workflows定义标准工作流程

Having Claude jump straight into code changes without planning creates rework. Claude might implement a solution that misses requirements, choose the wrong architectural approach, or make changes that break existing functionality.让Claude直接进行代码更改而不做计划会导致返工。Claude可能会实现一个遗漏需求的解决方案,选择错误的架构方法,或做出破坏现有功能的更改。

You need Claude to think before acting. Define standard workflows in your CLAUDE.md that Claude should follow for different types of tasks. A solid default workflow addresses four questions before making changes:你需要Claude在行动前思考。在CLAUDE.md中定义Claude应针对不同类型任务遵循的标准工作流程。一个可靠的默认工作流程在做出更改前解决四个问题:

  1. Is this a question about current state that requires investigation first?这是否是一个需要先进行调查的关于当前状态的问题?
  2. Does this need a detailed plan before implementation?这需要在实施前制定详细计划吗?
  3. What additional information is missing?缺少哪些额外信息?
  4. How will effectiveness be tested?如何测试有效性?

Specific workflows might include explore-plan-code-commit for features, test-driven development for algorithmic work, or visual iteration for UI changes. Document your testing requirements, commit message format, and any approval steps. When Claude knows your workflow upfront, it structures work to match your team's actual process rather than guessing.特定的工作流程可能包括:功能开发的探索-计划-编码-提交、算法工作的测试驱动开发、或UI更改的可视化迭代。记录你的测试要求、提交消息格式以及任何审批步骤。当Claude提前了解你的工作流程时,它会以匹配团队实际流程的方式组织工作,而不是猜测。

An example workflow instruction might be: 一个示例工作流程指令可能是:

1) Before modifying code in the following locations: X, Y, Z
	- Consider how it might affect A, B, C
	- Construct an implementation plan
	- Develop a test plan that will validate the following functions...

Additional tips for working with Claude Code 使用Claude Code的额外技巧

Beyond configuring your CLAUDE.md file, three additional techniques improve how you work with Claude Code.除了配置CLAUDE.md文件外,还有三种额外技巧可以改善你使用Claude Code的方式。

Keep context fresh保持上下文新鲜

Working with Claude Code over time accumulates irrelevant context. File contents from earlier tasks, command outputs that no longer matter, and tangential conversations fill Claude's context window. As the signal-to-noise ratio drops, Claude struggles to maintain focus on the current task.长时间使用Claude Code会积累不相关的上下文。早期任务的文件内容、不再重要的命令输出以及无关的对话会填满Claude的上下文窗口。随着信噪比下降,Claude难以保持对当前任务的专注。

Use /clear between distinct tasks to reset the context window. This removes accumulated history while preserving your CLAUDE.md configuration and Claude's ability to address new problems with fresh context. Think of it as closing one work session and opening another.在不同任务之间使用/clear来重置上下文窗口。这会清除积累的历史记录,同时保留你的CLAUDE.md配置和Claude以新上下文处理新问题的能力。可以将其视为关闭一个工作会话并打开另一个。

When you finish debugging authentication and switch to implementing a new API endpoint, clear the context. The authentication details no longer matter and distract from the new work.当你完成调试身份验证并切换到实现新API端点时,清除上下文。身份验证细节不再重要,并且会分散新工作的注意力。

Use subagents for distinct phases为不同阶段使用子代理

Long conversations accumulate context that interferes with new tasks. You've debugged a complex authentication flow, and now you need a security review of that same code. The debugging details color Claude's security analysis, potentially causing it to overlook issues or focus on already-resolved concerns.长时间的对话会积累干扰新任务的上下文。你调试了一个复杂的身份验证流程,现在需要对同一代码进行安全审查。调试细节会影响Claude的安全分析,可能导致它忽略问题或专注于已解决的担忧。

Tell Claude to use a subagent for distinct phases of work. Subagents maintain isolated context, preventing information from earlier tasks from interfering with new analysis. After implementing a payment processor, instruct Claude to "use a sub-agent to perform a security review of that code" rather than continuing in the same conversation.告诉Claude为不同的工作阶段使用子代理。子代理保持隔离的上下文,防止早期任务的信息干扰新分析。在实现支付处理器后,指示Claude“使用子代理对该代码进行安全审查”,而不是在同一个对话中继续。

Subagents work best for multistep workflows where each phase requires different perspectives. Implementation needs architectural context and feature requirements; security review needs fresh eyes focused solely on vulnerabilities. Context separation keeps both analyses sharp.子代理最适合每个阶段需要不同视角的多步骤工作流程。实现需要架构上下文和功能需求;安全审查需要仅关注漏洞的新视角。上下文分离使两种分析都保持敏锐。

Create custom commands创建自定义命令

Repetitive prompts waste time. You find yourself typing "review this code for security issues" or "analyze this for performance problems" over and over. Each time you need to remember the exact phrasing that gets good results.重复的提示浪费时间。你发现自己一遍又一遍地输入“审查此代码的安全问题”或“分析此代码的性能问题”。每次都需要记住能获得良好结果的确切措辞。

Custom slash commands store these as markdown files in your .claude/commands/ directory. Create a file named performance-optimization.mm with your preferred performance optimization prompt, and it becomes available as /performance-optimization in any conversation. Commands support arguments through $ARGUMENTS or numbered placeholders like $1 and $2, letting you pass specific files or parameters.自定义斜杠命令将这些存储为.claude/commands/目录中的markdown文件。创建一个名为performance-optimization.md的文件,包含你偏好的性能优化提示,它就会在对话中作为/performance-optimization可用。命令通过$ARGUMENTS或编号占位符(如$1和$2)支持参数,让你传递特定文件或参数。

For example, performance-optimization.md might look like this:例如,performance-optimization.md可能如下所示:

# Performance Optimization

Analyze the provided code for performance bottlenecks and optimization opportunities. Conduct a thorough review covering:

## Areas to Analyze

### Database & Data Access
- N+1 query problems and missing eager loading
- Lack of database indexes on frequently queried columns
- Inefficient joins or subqueries
- Missing pagination on large result sets
- Absence of query result caching
- Connection pooling issues

### Algorithm Efficiency
- Time complexity issues (O(n²) or worse when better exists)
- Nested loops that could be optimized
- Redundant calculations or repeated work
- Inefficient data structure choices
- Missing memoization or dynamic programming opportunities

### Memory Management
- Memory leaks or retained references
- Loading entire datasets when streaming is possible
- Excessive object instantiation in loops
- Large data structures kept in memory unnecessarily
- Missing garbage collection opportunities

### Async & Concurrency
- Blocking I/O operations that should be async
- Sequential operations that could run in parallel
- Missing Promise.all() or concurrent execution patterns
- Synchronous file operations
- Unoptimized worker thread usage

### Network & I/O
- Excessive API calls (missing request batching)
- No response caching strategy
- Large payloads without compression
- Missing CDN usage for static assets
- Lack of connection reuse

### Frontend Performance
- Render-blocking JavaScript or CSS
- Missing code splitting or lazy loading
- Unoptimized images or assets
- Excessive DOM manipulations or reflows
- Missing virtualization for long lists
- No debouncing/throttling on expensive operations

### Caching
- Missing HTTP caching headers
- No application-level caching layer
- Absence of memoization for pure functions
- Static assets without cache busting

## Output Format

For each issue identified:
1. **Issue**: Describe the performance problem
2. **Location**: Specify file/function/line numbers
3. **Impact**: Rate severity (Critical/High/Medium/Low) and explain expected performance degradation
4. **Current Complexity**: Include time/space complexity where applicable
5. **Recommendation**: Provide specific optimization strategy
6. **Code Example**: Show optimized version when possible
7. **Expected Improvement**: Quantify performance gains if measurable

If code is well-optimized:
- Confirm optimization status
- List performance best practices properly implemented
- Note any minor improvements possible

**Code to review:**
```
$ARGUMENTS
```

You don't need to write custom command files manually. Ask Claude to create them for you:你不需要手动编写自定义命令文件。让Claude为你创建它们:

Create a custom slash command called /performance-optimization that analyzes code for database query issues, algorithm efficiency, memory management, and caching opportunities.

Claude will write the markdown file to .claude/commands/performance-optimization.md, and the command will be available immediately.Claude会将markdown文件写入.claude/commands/performance-optimization.md,并且该命令将立即可用。

Start simple, expand deliberately从简单开始,有意识地扩展

It's tempting to create a comprehensive CLAUDE.md right away. Resist that urge.立即创建一个全面的CLAUDE.md很诱人。但请抵制这种冲动。

CLAUDE.md is added to Claude Code's context every time, so from a context engineering and prompt engineering standpoint, keep it concise. One option: break up information into separate markdown files and reference them inside the CLAUDE.md file.CLAUDE.md每次都会被添加到Claude Code的上下文中,因此从上下文工程和提示工程的角度来看,保持简洁。一种选择:将信息分解到单独的markdown文件中,并在CLAUDE.md文件中引用它们。

Don't include sensitive information, API keys, credentials, database connection strings, or detailed security vulnerability information—especially if you commit to version control. Since CLAUDE.md becomes part of Claude's system prompt, treat it as documentation that could be shared publicly.不要包含敏感信息、API密钥、凭据、数据库连接字符串或详细的安全漏洞信息——尤其是如果你要提交到版本控制。由于CLAUDE.md成为Claude系统提示的一部分,请将其视为可能公开共享的文档。

Make CLAUDE.md work for you让CLAUDE.md为你服务

CLAUDE.md files turn Claude Code from a general-purpose assistant into a tool configured specifically for your codebase. Start simple with basic project structure and build documentation, then expand based on actual friction points in your workflow.CLAUDE.md文件将Claude Code从通用助手转变为专门为你的代码库配置的工具。从基本的项目结构和构建文档开始,然后根据工作流程中的实际痛点进行扩展。

The most effective CLAUDE.md files solve real problems: they document the commands you type repeatedly, capture the architectural context that takes ten minutes to explain, and establish workflows that prevent rework. Your file should reflect how your team actually develops software—not theoretical best practices that sound good but don't match reality.最有效的CLAUDE.md文件解决实际问题:它们记录你反复输入的命令,捕捉需要十分钟解释的架构上下文,并建立防止返工的工作流程。你的文件应反映团队实际开发软件的方式——而不是听起来不错但与现实不符的理论最佳实践。

Treat customization as an ongoing practice rather than a one-time setup task. Projects change, teams learn better patterns, and new tools enter your workflow. A well-maintained CLAUDE.md evolves with your codebase, continuously reducing the friction of working with AI assistance on complex software.将定制视为持续的实践,而非一次性的设置任务。项目会变化,团队会学到更好的模式,新工具会进入你的工作流程。一个维护良好的CLAUDE.md会随着你的代码库而演变,持续减少在复杂软件上使用AI辅助的摩擦。

Get started with Claude Code today.立即开始使用Claude Code。

No items found.
Prev
0/5
Next
eBook

No items found.

Transform how your organization operates with Claude

See pricing
Contact sales

Get the developer newsletter

Product updates, how-tos, community spotlights, and more. Delivered monthly to your inbox.

Subscribe

Please provide your email address if you'd like to receive our monthly developer newsletter. You can unsubscribe at any time.

Thank you! You’re subscribed.
Sorry, there was a problem with your submission, please try again later.
Claude Code