让Claude Code更懂你:写好CLAUDE.md的8条实战经验
本文总结了8条通过优化CLAUDE.md让Claude Code更契合项目的实战经验,包括:将文件长度控制在200行内以避免信息过载;用“禁止引入的库”清单替代仅列出技术栈;制定可操作、可验证的编码规则(如使用named export、禁用any类型);将CLAUDE.md作为信息路由而非知识库;在敏感模块(如认证、支付)本地化配置;通过Hook强制执行而非依赖记忆;用MEMORY.md实现跨会话知识迁移;以及预先定义工作风格以减少重复指令。这些原则源自一线实践,附带具体代码示例和对比,适用于所有使用AI编程助手的工程师。
Many people new to Claude Code stuff everything into CLAUDE.md: project history, technical decisions, personal preferences, even company values. The result? Claude gets lost in 2000 lines of context, generates nonsensical output, and you have no idea why.
This article isn't about the structural spec of CLAUDE.md. It's about 8 hard-won lessons from real practice—which counter-intuitive approaches work better, and which pitfalls you only need to step in once.
Counter-intuitive: You think more information means Claude understands you better. In reality, more information means Claude is more likely to ignore what's truly important.
Boris Cherny, author of claude-code-best-practice, explicitly recommends: CLAUDE.md should not exceed 200 lines. This isn't arbitrary—Claude Code loads CLAUDE.md on every session, consuming context window. Every extra line you write crowds out space for Claude to understand your code.
Practical standards:
# ❌ Don't do this
## Project History
In 2023, our CTO proposed this idea at a hackathon...
(300 lines of company narrative + marketing copy)
# ✅ Do this
## Project Overview
B2B analytics dashboard for operations managers.
Core goal: shorten time from data to insight.
Optimization priority: load speed > interaction richness > visual flashiness.
Validation standard: A person unfamiliar with your project, after reading CLAUDE.md, can answer three questions in 30 seconds—what is this product? What's the tech stack? Where do new files go?
反直觉点:你觉得信息越多,Claude 越懂你。实际上,信息越多,Claude 越容易忽略真正重要的。
claude-code-best-practice 的作者 Boris Cherny 明确建议:CLAUDE.md 不要超过 200 行。这不是随便说的——Claude Code 每次会话都会加载 CLAUDE.md,它会吃掉上下文窗口。你写的每一行多余内容,都在挤占 Claude 理解你代码的空间。
实战标准:
# ❌ 不要这样
## 项目历史
2023 年,我们的 CTO 在 hackathon 上提出了这个想法...
(300 行的公司叙事 + 营销文案)
# ✅ 要这样
## Project Overview
B2B 分析仪表盘,面向运营经理。
核心目标:缩短「从数据到洞察」的时间。
优化优先级:加载速度 > 交互丰富度 > 视觉花哨。
验证标准:一个没看过你项目的人,读完 CLAUDE.md 能在 30 秒内回答三个问题——这是什么产品?技术栈是什么?新代码放哪里?
Counter-intuitive: You list your tech stack, thinking Claude won't go rogue. But Claude's knowledge cuts off at its training date—it doesn't know your project's historical baggage.
A CLAUDE.md without a 'forbidden list' is dangerous. Claude will, out of good intentions, introduce the 'best' solution it knows, which could completely conflict with your project.
## Tech Stack
- Next.js 15 App Router + TypeScript
- Tailwind CSS + shadcn/ui
- Supabase (auth + data)
Do NOT introduce unless explicitly requested:
- Redux (project migrated to React Context + Zustand)
- styled-components (full site Tailwind, no CSS-in-JS)
- Material UI (style conflict with shadcn/ui)
- MongoDB (data layer locked to PostgreSQL)
This rule is worth its weight in gold. It doesn't just save one correction—it prevents Claude from introducing incompatible dependencies without you noticing, causing the next 10 sessions to fix compatibility issues.
反直觉点:你列出了技术栈,以为 Claude 不会乱来。但 Claude 的知识截止到训练日,它不知道你的项目有历史包袱。
没有「禁止清单」的 CLAUDE.md 是危险的。Claude 会出于善意引入它「知道」的最优方案,但这个方案可能和你的项目完全冲突。
## Tech Stack
- Next.js 15 App Router + TypeScript
- Tailwind CSS + shadcn/ui
- Supabase(认证 + 数据)
Do NOT introduce unless explicitly requested:
- Redux(项目已迁移到 React Context + Zustand)
- styled-components(全站 Tailwind,不接受 CSS-in-JS)
- Material UI(与 shadcn/ui 样式冲突)
- MongoDB(数据层已锁定 PostgreSQL)
这条规则值千金。它节省的不是一次纠正,而是防止 Claude 在你没发现时引入了不兼容的依赖,导致后续 10 次会话都在修兼容性问题。
Counter-intuitive: 'Write clean code' sounds like a good rule, but to an AI it says nothing.
Claude doesn't understand 'clean'. It understands 'use named exports instead of default exports', 'components under 200 lines', 'async/await instead of promise chains'.
Compare:
# ❌ Vague—Claude can't execute
## Coding Rules
- Write clean code
- Keep it simple
- Focus on performance
# ✅ Specific—Claude can execute directly
## Coding Rules
- Use named exports (except route files)
- No `any` type; use generics or interfaces
- Single component under 200 lines (exceptions with justification)
- async/await over Promise chains
- Full variable names, no abbreviations (except id/url/ctx)
- Comments only when intent is non-obvious
- No commented-out code blocks or console.log
Test method: After reading this rule, can you tell within 5 seconds whether a piece of code complies? Yes—rule passes. No—rewrite it.
反直觉点:「写干净的代码」听起来像个好规则,但对 AI 来说等于没说。
Claude 不懂「干净」。它懂「用 named export 而不是 default export」「组件不超过 200 行」「async/await 不用 then 链」。
对比:
# ❌ 模糊——Claude 无法执行
## Coding Rules
- 写干净的代码
- 保持简洁
- 注重性能
# ✅ 具体——Claude 可以直接执行
## Coding Rules
- 使用 named export(路由文件除外)
- 禁止 any 类型,用泛型或接口替代
- 单个组件不超过 200 行(有充分理由可超)
- async/await 替代 Promise 链
- 变量名全拼,不缩写(除 id/url/ctx)
- 只在意图不明显时写注释
- 不留注释掉的代码块或 console.log
测试方法:读完这条规则后,你能不能在 5 秒内判断一段代码是否符合它?能——规则合格。不能——改写。
Counter-intuitive: You want to cram all architectural docs into CLAUDE.md. But CLAUDE.md's job isn't to store information—it's to tell Claude where to find it.
This is the dividing line between top-tier and average users. The average user's CLAUDE.md is a knowledge dump; the top-tier user's CLAUDE.md is a router.
## Project Context
- Architecture overview: `docs/architecture.md`
- Architecture Decision Records: `docs/adrs/`
- API docs: `docs/api.md`
- Deployment process: `docs/deploy.md`
Claude doesn't need to read all architecture docs in CLAUDE.md. It just needs to know: 'When I need architecture info, open docs/architecture.md.'
More advanced usage—Progressive Disclosure:
## Context Tiers
Tier 1 (loaded every time): CLAUDE.md — what the project is + how it works
Tier 2 (loaded on demand): docs/architecture.md, docs/api.md — Claude auto-reads while working
Tier 3 (ignored): docs/archive/ — don't touch unless explicitly asked
This way Claude doesn't waste context reading historical docs on irrelevant requests, but knows where to look when needed.
反直觉点:你想把所有架构文档塞进 CLAUDE.md。但 CLAUDE.md 的职责不是存储信息,而是告诉 Claude 去哪找信息。
这是顶级用户和普通用户的分水岭。普通用户的 CLAUDE.md 是知识梳理;顶级用户的 CLAUDE.md 是 router。
## Project Context
- 架构总览:`docs/architecture.md`
- 工程设计决策记录:`docs/adrs/`
- API 文档:`docs/api.md`
- 部署流程:`docs/deploy.md`
Claude 不需要在 CLAUDE.md 里读完所有架构文档。 它只需要知道「我需要架构信息时,打开 docs/architecture.md」。
更进阶的用法——渐进式上下文(Progressive Disclosure):
## Context Tiers
Tier 1(每次加载):CLAUDE.md — 项目是什么 + 怎么工作
Tier 2(按需加载):docs/architecture.md, docs/api.md — Claude 工作时自动读取
Tier 3(忽略):docs/archive/ — 除非明确要求,不碰
这样 Claude 不会在无关请求时浪费上下文读历史文档,但在需要时知道去哪找。
Counter-intuitive: There's only one CLAUDE.md, in the root directory. But some modules carry 10x the risk of others.
Place a local CLAUDE.md under src/auth/, src/payments/, infra/—Claude automatically loads it when operating in those directories. It's like installing guardrails in dangerous zones.
# src/auth/CLAUDE.md
## Security Hardlines
- Never modify token verification logic unless explicitly requested and reviewed
- Never introduce new auth methods without updating tests
- All auth-related changes must pass `pnpm test src/auth`
## Known Traps
- Magic link generation depends on `crypto.randomUUID()`, do not replace with other random methods
- Session stored in Redis, not memory—survives restarts
反直觉点:CLAUDE.md 只有一个,放根目录。但某些模块的风险比其他模块高 10 倍。
在 src/auth/、src/payments/、infra/ 下面各放一个本地 CLAUDE.md,Claude 在操作这些目录时会自动加载。这就像给危险区域装护栏。
# src/auth/CLAUDE.md
## 安全红线
- 绝不修改 token 验证逻辑,除非明确要求且经过 review
- 绝不引入新的认证方式而不更新测试
- 所有认证相关变更必须通过 `pnpm test src/auth` 全部测试
## 已知陷阱
- Magic link 生成依赖 `crypto.randomUUID()`,不要换成其他随机方法
- Session 存储在 Redis,不是内存——重启不会丢失
Counter-intuitive: You write testing rules, but Claude never runs tests after writing code—because it forgot.
Claude's memory is unreliable. Hooks are reliable. Turn rules in CLAUDE.md into hook triggers:
## Hooks & Quality Gates
The following rules are enforced by `.claude/hooks/`, not reminders:
- Auto-format after each edit (PreToolUse hook → prettier)
- Auto-run tests after core module changes (PostToolUse hook → vitest related)
- No direct edits to `src/auth/`, `src/billing/`, `prisma/migrations/` without confirmation
Corresponding hook example:
// .claude/hooks/pre-tool-use.json
{
"hooks": [
{
"matcher": "Edit|Write",
"command": "npx prettier --write ${CLAUDE_FILES}",
"on_failure": "warn"
}
]
}
Hooks are the enforcement layer for CLAUDE.md rules. Rules in CLAUDE.md say 'please remember'; rules backed by hooks say 'you must'.
反直觉点:你写了测试规则,但 Claude 写完代码从来不跑测试——因为它忘了。
Claude 的记忆不可靠。Hook 可靠。把 CLAUDE.md 里的规则变成 Hook 的触发条件:
## Hooks & Quality Gates
以下规则由 `.claude/hooks/` 强制执行,不是提醒:
- 每次编辑后自动格式化(PreToolUse hook → prettier)
- 核心模块变更后自动跑测试(PostToolUse hook → vitest related)
- 禁止直接编辑 `src/auth/`、`src/billing/`、`prisma/migrations/` 而不先确认
对应 Hook 示例:
// .claude/hooks/pre-tool-use.json
{
"hooks": [
{
"matcher": "Edit|Write",
"command": "npx prettier --write ${CLAUDE_FILES}",
"on_failure": "warn"
}
]
}
Hook 是 CLAUDE.md 规则的强制执行层。写在 CLAUDE.md 里的规则是「请记住」;配了 Hook 的规则是「你必须」。
Counter-intuitive: Every new session, Claude re-learns your project like it has amnesia. But you don't need a complex vector database to solve this.
Add an instruction in CLAUDE.md for Claude to maintain a MEMORY.md itself:
## Memory
`MEMORY.md` records key insights, best practices, and known pitfalls discovered in previous tasks.
Before each new task, read MEMORY.md first.
After each task, if there are new discoveries
This is simpler, more controllable, and Git-trackable than any 'AI long-term memory MCP'. Cost: one file. Benefit: Claude retains the most valuable 5% of context across sessions.
Counter-intuitive: You should train Claude, not ask it 'Can you help me do X?' every time. Let CLAUDE.md carry your working style, so Claude knows what you hate from the very first conversation.
Real-world summary from Claude Code Cowork—a great CLAUDE.md includes 'who you are' and 'what you hate':
## My Working Style
- Propose a plan first, don't write code directly
- List options when uncertain, don't guess
- Ask before major changes, execute minor optimizations directly
- Don't use fluff like 'Great question!' or 'I'd be happy to help!'
- Respond in Chinese, code comments in English
- Use absolute paths for files, not relative paths
These 6 lines eliminate the first 5 messages of every new session. Claude knows from the first sentence what you care about, what you hate, and what interaction rhythm you expect.
反直觉点:你应该训练 Claude,不是每次问它「你能帮我做 X 吗」。你应该让 CLAUDE.md 承载你的工作风格,让 Claude 在第一次对话时就知道你讨厌什么。
来自 Claude Code Cowork 的实战总结——一个优秀的 CLAUDE.md 里应该有「你是谁」和「你讨厌什么」:
## My Working Style
- 先给方案,不要直接写代码
- 不确定时列出选项,不要猜测
- 重大变更前先问,小优化可以直接执行
- 不要用「Great question!」「I'd be happy to help!」这类废话
- 回复用中文,代码注释用英文
- 文件路径用绝对路径,不要相对路径
这 6 行省掉了你每次新会话的前 5 条消息。Claude 从第一句就知道你在乎什么、讨厌什么、期望什么交互节奏。
CLAUDE.md isn't a file you write once and leave. It's alive—every time you discover a pitfall Claude repeatedly steps in, or distill an effective rule, update it. Look back a month later, and you'll find Claude has evolved from a rookie intern into a senior engineer who truly understands your project.
CLAUDE.md 不是一次写完就放那的文件。它是活的——你每发现一个 Claude 反复踩的坑、每总结一条有效的规则,都应该更新进去。一个月后回头看,你会发现 Claude 从一个菜鸟实习生,变成了真正懂你项目的高级工程师。