
https://www.anthropic.com/engineering/claude-code-best-practices
You can place CLAUDE.md files in several locations:
1、The root of your repo, or wherever you run claude from (the most common usage). Name it CLAUDE.md and check it into git so that you can share it across sessions and with your team (recommended), or name it CLAUDE.local.md and .gitignore it
2、Any parent of the directory where you run claude. This is most useful for monorepos, where you might run claude from root/foo, and have CLAUDE.md files in both root/CLAUDE.md and root/foo/CLAUDE.md. Both of these will be pulled into context automatically
3、Any child of the directory where you run claude. This is the inverse of the above, and in this case, Claude will pull in CLAUDE.md files on demand when you work with files in child directories
4、Your home folder (~/.claude/CLAUDE.md), which applies it to all your claude sessions
When you run the /init command, Claude will automatically generate a CLAUDE.md for you.
根据 Anthropic 官方工程实践,我来为您重新进行清晰、准确的总结。
Claude 会智能地从多个位置发现并加载 CLAUDE.md 文件,形成一个上下文层次结构。其发现逻辑与优先级可用下图概括:
flowchart TD
A[Claude 上下文加载机制]
A --> B["从当前工作目录 (CWD) 开始"]
B --> C["查找并加载 ./CLAUDE.md<br>(核心配置)"]
B --> D["向上遍历父目录"]
D --> E["查找并加载 ../CLAUDE.md<br>(例如: Monorepo 全局配置)"]
B --> F["向下探索子目录"]
F --> G["按需加载 ./subdir/CLAUDE.md<br>(当操作深入该子目录时)"]
A --> H["最后加载用户全局配置"]
H --> I["加载 ~/.claude/CLAUDE.md<br>(个人偏好与基线设置)"]
C --> J["最终上下文: <br>合并所有找到的配置<br>(通常更具体、更局部的配置优先级更高)"]
E --> J
G --> J
I --> J•路径:你的项目根目录/CLAUDE.md•用途:定义该项目的特定规范、技术栈、命令和结构。这是共享团队知识的最重要文件。•实践建议:
•命名为 CLAUDE.md 并提交到 Git,以便与团队成员共享。•命名为 CLAUDE.local.md 并将其添加到 .gitignore,用于存储纯个人、不想共享的项目备注。
•路径:例如,如果你在 /monorepo/project-a 目录下工作,Claude 也会读取 /monorepo/CLAUDE.md。•用途:在Monorepo(单体仓库)中非常有用。可以在根目录设置全局通用规则,然后在子项目中设置更具体的规则。两者会自动合并到上下文中。
•路径:当前工作目录的任意子目录中,如 你的项目根目录/docs/CLAUDE.md。•用途:当你操作或询问深入到某个特定子目录(如 docs、src/components)时,Claude 会按需将该子目录的 CLAUDE.md 拉取到上下文中,提供最精准的局部上下文。
•路径:~/.claude/CLAUDE.md•用途:包含你个人所有会话的基线设定和偏好(如编码风格、沟通偏好、常用工具链)。此文件中的设置会应用于你启动的每一个Claude会话。
1.二者兼用:你应该同时使用 ~/.claude/CLAUDE.md(个人全局偏好)和 ./CLAUDE.md(项目特定规则)。2.优先级:通常,更具体、更局部的配置会覆盖更全局的配置。例如,项目根目录的 CLAUDE.md 设置会覆盖用户主目录中的冲突设置。3.自动生成:在项目根目录运行 /init 命令,Claude 会自动分析你的代码库并为你生成一个初步的 CLAUDE.md 文件草稿,你可以在此基础上修改和完善。4.共享配置:为了团队协作,强烈建议将项目根目录的 CLAUDE.md 提交到版本控制中,使其成为项目文档的一部分。
总而言之,官方设计了一套非常灵活的系统,允许你通过在不同层级放置 CLAUDE.md 文件,来为不同范围(个人、项目、子项目)的会话提供精准的上下文。