如何编写 CLAUDE.md:从入门到精通的完整指南
如何编写 CLAUDE.md:从入门到精通的完整指南
1. 什么是 CLAUDE.md?为什么需要它?
想象一下,你每天上班时,都需要向一个新同事从头解释一遍项目的基本情况:代码规范、测试命令、项目结构、注意事项……这个过程既浪费时间,又容易出错。
CLAUDE.md 就像是给 AI 助手的一份“项目入职手册”。它是一个 Markdown 格式的文本文件,Claude Code(Anthropic 公司推出的 AI 编程助手)会在每次会话开始时自动读取它。这样,Claude 就能从第一条消息起就了解你的项目,无需你重复解释。
通俗理解:CLAUDE.md 是 Claude 的“长期记忆”。你写在里面的内容,Claude 每次都会认真阅读并尽量遵守。
为什么需要它?
- 保持一致性:确保 Claude 每次都按照相同的规范工作
- 节省时间:不用反复说明项目细节
- 团队共享:通过 Git 提交,整个团队都能让 AI 按照统一标准工作
- 跨越会话:即使在长时间对话或重启会话后,Claude 仍然记得这些规则
2. CLAUDE.md 如何工作?(技术背景解析)
2.1 加载机制:文件从哪里来?
Claude Code 有一套分层发现系统,按照优先级从高到低加载多个 CLAUDE.md 文件:
| 优先级 | 文件位置 | 用途 | 是否提交到 Git |
|---|---|---|---|
| 最高 | 组织级策略(如 /Library/Application Support/ClaudeCode/CLAUDE.md) |
全公司统一规则 | 否 |
| 高 | 用户全局(~/.claude/CLAUDE.md) |
个人跨项目偏好 | 否 |
| 中 | 项目根目录(./CLAUDE.md 或 ./.claude/CLAUDE.md) |
团队共享规则 | 是 |
| 低 | 本地项目(./CLAUDE.local.md) |
个人项目特定设置 | 否(自动加入 .gitignore) |
| 按需 | 父目录(向上查找) | 大仓(monorepo)中上层规范 | 视情况 |
| 按需 | 子目录(需要时才加载) | 包或模块特定规则 | 视情况 |
技术提示:父目录的文件在启动时加载,子目录的文件在 Claude 访问该目录时才加载。这种设计既保证了全局规范,又节省了上下文 token。
2.2 注入过程:文件内容如何进入 AI 的“大脑”?
Claude Code 在每次会话开始时,会动态组装系统提示(system prompt),组装顺序大致为:
- 核心代理指令(工具描述、安全准则)
- 环境配置(操作系统、工作目录、可用工具)
- CLAUDE.md 内容(按上述层次结构加载)
- 自动记忆 MEMORY.md(仅前 200 行)
- 会话上下文(对话历史、压缩摘要)
重要理解:CLAUDE.md 的内容是以建议性方式注入的,而不是强制性配置。Claude 会尽力遵守,但如果指令模糊或冲突,它有权判断是否适用。
2.3 提示缓存:为什么长文件不会一直很贵?
Claude Code 使用 Anthropic 的提示缓存技术。CLAUDE.md 内容会缓存在系统提示前缀中:
- 首次调用:消耗完整的 token(例如 1500 tokens)
- 后续调用:从缓存读取,成本降低约 90%(几乎为零)
这意味着你可以放心地编写适当长度的 CLAUDE.md,不用担心后续成本。
3. 实战示例:6 个不同场景的 CLAUDE.md
3.1 小型项目:极简版(约 25 行)
适用于个人项目或小型原型,只包含 Claude 无法从代码中推断出的信息。
## Commands
- Dev: `bun run dev` (port 3002, not 3000)
- Build: `bun run build && bun run typecheck:fast`
- Test: `bun test` (not npm test)
- Lint: `bun run lint`
## Key Conventions
- TypeScript strict mode — no `any` types
- Server components by default; client components only when needed
- All DB access through Drizzle ORM, never raw SQL
- Use `bun` for all package operations, not npm or yarn
## Gotchas
- .env.local required locally — see docs/setup.md
- Port 5432 must be free for Postgres
- Never commit .env.local
3.2 大仓项目(Monorepo):根级文件(约 60 行)
根文件保持简洁,只描述整体结构和工作流,具体细节放入各个包的 CLAUDE.md。
# Monorepo Structure
- `packages/api` — Express API, Node 20, TypeScript
- `packages/web` — Next.js 15 frontend
- `packages/shared` — Shared types and utilities
- `packages/workers` — Background job processors (BullMQ)
Each package has its own CLAUDE.md with package-specific rules.
## Root Commands
- `pnpm install` from root to install all packages
- `pnpm --filter api dev` to run API dev server
- `pnpm --filter web dev` to run web dev server
- `pnpm build` builds all packages in dependency order
- `pnpm test` runs all test suites
## Cross-Package Rules
- Shared types live in `packages/shared`, not copied across packages
- Breaking changes to shared types require updating all consumers
- Use `pnpm --filter <package> <command>` to scope commands
- Changesets for version management: `pnpm changeset`
## Git Conventions
- Branch: `feat/`, `fix/`, `chore/` prefixes
- Commit format: conventional commits
- PRs require passing CI before merge
## What NOT to Do
- Do not install packages at the root that belong in a package
- Do not import directly between packages — use the shared package
- Do not run `npm` or `yarn` — this project uses pnpm workspaces
3.3 Next.js 应用:架构版(约 80 行)
Next.js 项目有许多独特概念(App Router、服务端/客户端组件、Server Actions),非常适合用 CLAUDE.md 规范。
# Project: SaaS Dashboard (Next.js 15, App Router)
## Commands
- `bun run dev` — start dev server (port 3000)
- `bun run build` — production build
- `bun run typecheck:fast` — type check without emit
- `bun run lint` — ESLint
- `bun run db:push` — push Drizzle schema changes
- `bun run db:studio` — open Drizzle Studio
## Architecture
- `src/app/` — App Router pages and layouts
- `src/app/(dashboard)/` — authenticated route group
- `src/app/(marketing)/` — public marketing pages
- `src/app/api/` — API routes
- `src/components/ui/` — shared UI components (Radix + Tailwind)
- `src/lib/` — utilities, DB client, server-side helpers
- `src/lib/db/schema.ts` — Drizzle schema (source of truth for DB)
## Component Rules
- Server components by default — never add "use client" without reason
- Client components: interactivity, browser APIs, useState/useEffect only
- Use server actions for mutations (files named actions.ts)
- Never import server-only code in client components
## Database
- All DB access through Drizzle in server components or server actions
- Use `db/schema.ts` types — never raw SQL strings
- Run `bun run db:push` after schema changes
## Authentication
- Clerk handles auth — `auth()` and `currentUser()` from `@clerk/nextjs`
- Protected routes: middleware in `middleware.ts` using clerkMiddleware
- Never check auth in client components — use server components or API routes
## Payments
- Stripe for subscriptions — `src/lib/stripe.ts`
- Webhook handler: `src/app/api/webhooks/stripe/route.ts`
- Never expose secret keys client-side
## Before Pushing
Run `bun run typecheck:fast` and `bun run lint`. Both must pass.
3.4 Python 机器学习项目:环境版(约 70 行)
ML 项目对环境、GPU、数据路径有特殊要求,Claude 无法从代码中推断这些。
# Project: Training Pipeline (PyTorch, Python 3.11)
## Environment Setup
- Virtual env: `source .venv/bin/activate` before any Python commands
- Dependencies: `pip install -e ".[dev]"` for dev install with extras
- GPU: training scripts assume CUDA 12.1 — check `torch.cuda.is_available()`
## Commands
- Run training: `python train.py --config configs/base.yaml`
- Run tests: `pytest tests/ -v --tb=short`
- Lint: `ruff check . && ruff format --check .`
- Type check: `mypy src/ --ignore-missing-imports`
- Format: `ruff format .`
## Project Structure
- `src/models/` — model architecture definitions
- `src/data/` — dataset classes and preprocessing
- `src/training/` — training loops and optimizers
- `configs/` — YAML config files (Hydra)
- `scripts/` — one-off analysis and eval scripts
- `tests/` — unit and integration tests
## Code Conventions
- Type hints on all public functions
- Docstrings on all public classes and non-trivial functions
- Use `loguru` for logging, not print statements
- Experiments tracked in MLflow — call `mlflow.log_params()` in train.py
- No hardcoded paths — use Hydra config or pathlib relative to project root
## Data
- Raw data: `data/raw/` (never modify, gitignored)
- Processed data: `data/processed/` (gitignored)
- Sample data for tests: `tests/fixtures/` (small, committed)
- Do not load full datasets in unit tests
## GPU Note
Tests run on CPU by default (`--device cpu` flag). GPU-only tests marked with
`@pytest.mark.gpu` and skipped in CI. Run locally with `pytest -m gpu`.
3.5 基础设施/DevOps:安全版(约 60 行)
基础设施代码需要强力的安全护栏,明确告诉 Claude 哪些操作绝对禁止。
# Project: Infrastructure (Terraform + Kubernetes, AWS)
## Commands
- `terraform plan` — always before apply
- `terraform apply` — requires explicit user confirmation
- `kubectl apply -f` — dry-run first with `--dry-run=client`
- `make lint` — tflint + tfsec + yamllint
- `make test` — terratest unit tests
## Safety Rules
- NEVER run `terraform destroy` without explicit user instruction
- NEVER modify production state files directly
- ALWAYS run `terraform plan` before proposing apply
- ALWAYS show plan output to user before suggesting apply
- Do not delete resources — prefer disabling or draining first
## Repository Structure
- `terraform/` — all Terraform modules
- `terraform/modules/` — reusable modules
- `terraform/environments/` — environment-specific configs (dev, staging, prod)
- `k8s/` — Kubernetes manifests (Kustomize)
- `scripts/` — operational scripts
- `docs/` — runbooks and architecture docs
## Conventions
- All secrets through AWS Secrets Manager or Parameter Store — never in code
- Resource naming: `{project}-{env}-{resource-type}`
- Tags: all resources require `project`, `environment`, and `owner` tags
- Modules: each module in its own directory with README.md
## AWS Account IDs (for context only — do not hardcode)
- Dev: account alias `mycompany-dev`
- Prod: account alias `mycompany-prod`
- Cross-account access: use IAM role assumption, never long-lived keys
3.6 集成 Hooks:自动化版
当项目使用了 Claude Code 的钩子(hooks),可以在 CLAUDE.md 中说明哪些任务已经自动处理。
# Project: API Service (Node.js, TypeScript)
## Commands
- `npm run dev` — start dev server with hot reload
- `npm test` — Jest unit tests
- `npm run test:e2e` — Playwright e2e tests
- `npm run build` — compile TypeScript
## Automated by Hooks (do not do manually)
The following happen automatically via .claude/settings.json hooks:
- ESLint + Prettier run after every file edit (PostToolUse: Write)
- TypeScript compile check runs after every file edit
- Git staging is blocked on src/db/migrations/ — ask before touching
## Code Conventions
- Async/await throughout — no raw Promise chains
- Error handling: throw typed errors, not string messages
- All routes validated with Zod before handler logic
- Logging: pino logger only, structured JSON, never console.log
## Project Structure
- `src/routes/` — route handlers
- `src/middleware/` — Express middleware
- `src/services/` — business logic
- `src/db/` — Drizzle schema and migrations
- `src/types/` — TypeScript type definitions
4. 进阶技巧与最佳实践
4.1 使用 .claude/rules/ 目录拆分规则
当项目变得复杂时,可以将规则拆分成多个文件,甚至按文件路径限定生效范围。
示例:.claude/rules/api-design.md
---
paths:
- "src/api/**/*.ts"
- "src/handlers/**/*.ts"
---
# API Design Rules
- All handlers return { data, error } shape
- Use zod for request body validation
- Include OpenAPI JSDoc on every public endpoint
- Rate limit headers on all routes
4.2 使用 @import 引用其他文件
你可以在 CLAUDE.md 中引用其他 Markdown 或纯文本文件,它们会被内联展开。
See @README.md for project overview and @package.json for available commands.
# Additional Instructions
- Git workflow: @docs/git-workflow.md
- Personal overrides: @~/.claude/my-project-overrides.md
限制:最多支持 5 层递归导入,避免循环引用。
4.3 长度控制:为什么 200 行是黄金标准?
Anthropic 官方建议每个 CLAUDE.md 文件控制在 200 行以内。原因不是 token 成本(2000 tokens 相对于 200K 上下文很小),而是遵循率。
研究表明,前沿大语言模型可靠地遵循约 150-200 条不同的指令。Claude Code 的内置系统提示已有约 50 条指令,所以你实际可用的指令预算约为 100-150 项。超过这个数量,Claude 开始“遗忘”指令——不是因为 token 溢出,而是因为指令密度分散了注意力。
如何判断过长?
- Claude 不断重复违反某个规则
- Claude 询问已经在 CLAUDE.md 中回答过的问题
- 指令之间存在矛盾
- 新团队成员觉得维护文件比直接和 Claude 对话还麻烦
解决方案:
- 使用
@import将详细内容移到单独文件 - 使用
.claude/rules/*.md按路径拆分 - 将格式强制类规则移到 hooks(确定性执行)
- 将任务特定工作流移到 skills
4.4 CLAUDE.md vs 自动记忆 vs Hooks
Claude Code 有三套互补的记忆机制:
| 机制 | 谁写入 | 内容 | 加载方式 | 是否团队共享 |
|---|---|---|---|---|
| CLAUDE.md | 你(人工) | 规则和指令 | 每次会话完整加载 | 是(通过 Git) |
| 自动记忆 (MEMORY.md) | Claude(自动) | 学习到的模式和偏好 | 仅前 200 行,详情按需加载 | 否(仅本地) |
| Hooks | 你(配置文件) | 确定性命令 | 特定事件触发 | 是(通过 settings.json) |
实战建议:
- 需要判断力的内容 →
CLAUDE.md - 必须无条件执行的内容(如自动格式化) → Hooks
- 个人探索发现的项目模式 → 让 Claude 写入自动记忆
4.5 压缩(Compaction)行为
当对话很长时,Claude Code 会运行压缩,总结历史并丢弃冗余细节。
关键点:
- ✅ CLAUDE.md 完全存活:压缩后会从磁盘重新读取,完整注入
- ❌ 会话中口头说的指令会丢失:如果没有写入 CLAUDE.md,压缩后可能被遗忘
最佳实践:如果想让 Claude 长期记住某件事,务必写入 CLAUDE.md 或要求它保存到自动记忆。
你甚至可以在 CLAUDE.md 中指导压缩行为:
## Session Notes
When compacting, always preserve:
- The full list of files modified in this session
- Any failing tests and their error messages
- Current migration state if db schema work is in progress
- Any architectural decisions made in this session
5. 常见错误与解决方案
5.1 重复 Claude 已知的常识
错误示例:
- Use 2-space indentation for JavaScript (PEP 8标准)
- React components should be named with PascalCase
为什么错:标准语言规范(PEP 8、TypeScript 模式、常见 React 模式)已经在 Claude 的训练数据中。重复这些浪费指令预算。
正确做法:只写与默认不同,或 Claude 无法从代码库推断的内容。
5.2 将格式强制放在 CLAUDE.md 而非 Hooks
错误示例:
- Always run Prettier after editing files
- Run ESLint before committing
为什么错:CLAUDE.md 是建议性的,Claude 可能忘记或判断“没必要”。格式检查应该是确定性的。
正确做法:在 .claude/settings.json 中配置 PostToolUse hook:
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "prettier --write $CLAUDE_TOOL_RESULT_PATH"
}]
}]
}
}
5.3 从不修剪,文件不断膨胀
问题:团队不断添加规则,但很少删除旧规则。3 个月后 CLAUDE.md 达到 300 行,但其中 240 行是“死重”。
解决方案:每几周审查一次。对每一行问自己:“如果删除这行,Claude 会犯错吗?”如果答案是否定的,就删除或移到路径限定规则中。
5.4 在 CLAUDE.md 中放入密钥或敏感信息
错误示例:
- Database password: mysecret123
- API_KEY = "sk-live_abc123"
为什么错:CLAUDE.md 会被提交到 Git,对所有团队成员可见,甚至可能在公开仓库中泄露。
正确做法:使用环境变量,在 CLAUDE.md 中只引用变量名:
- Database connection uses DATABASE_URL environment variable
- API keys are in process.env.API_KEY
5.5 大仓中文件冲突
问题:根 CLAUDE.md 说“使用 2 空格缩进”,但 packages/api/CLAUDE.md 说“使用 4 空格缩进”。Claude 会任意选择一个,导致不一致。
解决方案:
- 在根文件中设定全局标准
- 子目录只添加该目录特有的、不与全局冲突的规则
- 定期审计冲突
- 使用
claudeMdExcludes设置排除不相关的文件
6. CLAUDE.md 与其他工具的对比
| 特性 | CLAUDE.md | AGENTS.md | .cursorrules / .mdc | GEMINI.md |
|---|---|---|---|---|
| 所属工具 | Claude Code (Anthropic) | Codex, Cursor, Copilot, Gemini 等 | Cursor IDE | Gemini CLI (Google) |
| 发现方法 | 从 CWD 向上 + 子目录按需 | 从 Git 根向下到 CWD | 项目根或 .cursor/rules/*.mdc | CWD → 项目根 → 家目录 |
| 全局作用域 | ~/.claude/CLAUDE.md |
~/.codex/AGENTS.md |
无 | ~/.gemini/GEMINI.md |
| 多文件支持 | 是(.claude/rules/*.md) |
否(每目录一个) | 是(.cursor/rules/*.mdc) |
跨层级合并 |
| 路径限定规则 | 是(paths frontmatter) | 否 | 是(globs frontmatter) | 否 |
| 导入语法 | @path/to/file |
无 | 无 | 无 |
| 覆盖机制 | CLAUDE.local.md |
AGENTS.override.md |
@ruleName 手动包含 |
用户提示覆盖 |
何时使用 AGENTS.md? 如果你的团队使用多个 AI 工具(Cursor 做 IDE 工作、Codex 做云任务、Claude Code 做终端工作),共享的 AGENTS.md 可以减少工具间的行为差异。Claude Code 也会读取 AGENTS.md,但原生 CLAUDE.md 功能更丰富。
7. 总结与行动清单
核心要点回顾
- CLAUDE.md 是建议性配置,不是强制性规则。质量比数量重要。
- 控制在 200 行以内,超过会导致遵循率下降。
- 使用层级结构:根文件放全局规范,子目录或
.claude/rules/放特定规则。 - 结合 Hooks 实现确定性操作(格式化、危险命令阻止)。
- 定期修剪,删除过时或无效的指令。
- 永远不要放密钥,使用环境变量代替。
你的第一步行动清单
对于个人项目(今天就能做):
- 在项目根目录创建
CLAUDE.md - 写入 3-5 条最核心的规则(构建命令、代码风格、常见陷阱)
- 与 Claude 对话,观察它是否遵循
- 根据反馈调整
对于团队项目(本周完成):
- 与团队讨论,确定 10-15 条最重要的项目规范
- 创建根
CLAUDE.md并提交到 Git - 为有特殊规则的子目录创建各自的
CLAUDE.md - 配置必要的 hooks(如自动格式化)
- 建立季度审查机制,定期修剪文件
最后一句箴言
“CLAUDE.md 不是越详细越好,而是越有效越好。每一条规则都应该像代码一样被审视、测试和维护。”
现在,你已经掌握了编写 CLAUDE.md 的全部知识。去为你的项目创建这份宝贵的“AI 入职手册”吧!🚀