第 07 期 | 编写 CLAUDE.md:给 AI 的持久层项目简报

更新于 2026/4/5

🎯 学习目标

学完本期你将掌握:

  1. CLAUDE.md 的作用原理与文件加载机制
  2. 如何编写高效的项目指令
  3. Auto Memory 自动记忆功能的配置与管理
  4. .claude/rules/ 目录化规则组织

📖 核心概念讲解

7.1 为什么需要 CLAUDE.md?

每次你启动一个新的 Claude Code 会话,它对你的项目 一无所知。它会通过 GlobRead 去探索,但这很耗时且不精确。

CLAUDE.md 就是你写给 Claude 的 项目简报——它在每次会话开始时自动加载到上下文中,让 Claude 从第一秒就知道:

  • 这个项目是什么
  • 用了什么技术栈
  • 有哪些硬性规矩
  • 常用命令是什么

7.2 CLAUDE.md 的放置位置与优先级

文件位置                          作用域          加载时机
──────────────────────────────   ──────────     ──────────
/Library/Application Support/    系统级         始终加载(管理员设定)
  ClaudeCode/CLAUDE.md

~/.claude/CLAUDE.md              用户级         始终加载(个人偏好)

./CLAUDE.md                      项目级         进入项目目录时加载
./.claude/CLAUDE.md              项目级(备选)    同上

./src/billing/CLAUDE.md          子目录级       Claude 访问该目录时加载

📚 官方文档参考: How Claude remembers your project

7.3 引用其他文件 (@import)

CLAUDE.md 支持用 @ 语法引入其他文件作为上下文:

# 项目简报

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

## Git 工作流
- 遵循 @docs/git-instructions.md

## 个人偏好
- @~/.claude/my-personal-style.md

7.4 Auto Memory(自动记忆)

除了手写 CLAUDE.md,Claude Code 还有 Auto Memory 功能——它会在会话过程中自动保存你纠正过的偏好:

场景示例:
你:别用分号
Claude:好的,以后不加分号
→ 自动保存到 ~/.claude/memory.json:
  "在此项目中不使用 JavaScript 分号"

💻 模拟 Claude TUI 交互

场景 1:初始化 CLAUDE.md

$ cd ~/my-project
$ claude

> /init

╭─ Claude ─────────────────────────────────────────────╮
│                                                      │
│  🔍 Tool: Read (package.json)                        │
│  🔍 Tool: Glob (**/*.{ts,tsx,js,jsx})                │
│  🔍 Tool: Read (tsconfig.json)                       │
│  🔍 Tool: Read (.eslintrc.json)                      │
│  🔍 Tool: Glob (**/Dockerfile)                       │
│  🔍 Tool: Read (.github/workflows/*.yml)             │
│                                                      │
│  我已分析了你的项目结构,生成了以下 CLAUDE.md:       │
│                                                      │
│  ⚙️ Tool: Write → CLAUDE.md                          │
│  ╭─ NEW FILE ──────────────────────────────────╮     │
│  │ # Project: my-project                       │     │
│  │                                              │     │
│  │ ## Overview                                  │     │
│  │ E-commerce platform built with Next.js 14   │     │
│  │ and Express API, deployed on Vercel +        │     │
│  │ Railway.                                     │     │
│  │                                              │     │
│  │ ## Tech Stack                                │     │
│  │ - Frontend: Next.js 14 (App Router) + React │     │
│  │ - Backend: Express + Prisma + PostgreSQL    │     │
│  │ - Styling: Tailwind CSS                      │     │
│  │ - Testing: Vitest + Playwright              │     │
│  │                                              │     │
│  │ ## Commands                                  │     │
│  │ - `pnpm dev` — start dev servers            │     │
│  │ - `pnpm test` — run unit tests              │     │
│  │ - `pnpm build` — production build           │     │
│  │ - `pnpm db:push` — push schema changes      │     │
│  │                                              │     │
│  │ ## Rules                                     │     │
│  │ - Use TypeScript strict mode                 │     │
│  │ - 2-space indentation                        │     │
│  │ - No default exports (use named exports)     │     │
│  │ - Commit messages follow Conventional        │     │
│  │   Commits format                             │     │
│  ╰──────────────────────────────────────────────╯     │
│                                                      │
│  ✅ CLAUDE.md 已创建!                                │
│  你可以根据需要编辑补充。                             │
│                                                      │
╰──────────────────────────────────────────────────────╯

场景 2:CLAUDE.md 生效的效果

> 创建一个新的 API 路由处理用户个人信息更新

╭─ Claude ─────────────────────────────────────────────╮
│                                                      │
│  📝 Loaded context from CLAUDE.md:                   │
│  • TypeScript strict mode ✓                          │
│  • Named exports ✓                                   │
│  • Conventional Commits ✓                            │
│                                                      │
│  ⚙️ Tool: Write → src/routes/profile.ts              │
│  ╭─ NEW FILE ──────────────────────────────────╮     │
│  │ import { Router, Request, Response }         │     │
│  │   from 'express';                            │     │
│  │ import { z } from 'zod';                     │     │
│  │ import { prisma }                            │     │
│  │   from '@my-project/db';                     │     │
│  │ import { authMiddleware }                    │     │
│  │   from '../middleware/auth';                  │     │
│  │                                              │     │
│  │ // ✅ Named export (no default)              │     │
│  │ export const profileRouter = Router();       │     │
│  │                                              │     │
│  │ const updateSchema = z.object({              │     │
│  │   name: z.string().min(1).max(100),          │     │
│  │   bio: z.string().max(500).optional(),       │     │
│  │ });                                          │     │
│  │                                              │     │
│  │ // ✅ 2-space indentation                    │     │
│  │ profileRouter.patch(                         │     │
│  │   '/profile',                                │     │
│  │   authMiddleware,                            │     │
│  │   async (req: Request, res: Response) => {   │     │
│  │     const data = updateSchema.parse(         │     │
│  │       req.body                               │     │
│  │     );                                       │     │
│  │     const user = await prisma.user.update({  │     │
│  │       where: { id: req.userId },             │     │
│  │       data,                                  │     │
│  │     });                                      │     │
│  │     res.json({ ok: true, user });            │     │
│  │   }                                          │     │
│  │ );                                           │     │
│  ╰──────────────────────────────────────────────╯     │
│                                                      │
│  注意:我遵循了 CLAUDE.md 中的规则:                  │
│  ✅ TypeScript strict mode                            │
│  ✅ Named export (非 default export)                  │
│  ✅ 2-space indentation                               │
│  ✅ 使用了项目中已有的 prisma + zod 依赖             │
│                                                      │
╰──────────────────────────────────────────────────────╯

场景 3:管理自动记忆

> /memory

╭─ Auto Memory ────────────────────────────────────────╮
│                                                      │
│  📁 Storage: ~/.claude/memory.json                   │
│                                                      │
│  Saved memories for this project:                    │
│  1. "不使用分号 (no semicolons)"                     │
│  2. "API 返回格式统一为 { ok: boolean, data: T }"   │
│  3. "错误处理使用 AppError 自定义类"                 │
│  4. "数据库查询放在 services/ 目录"                  │
│                                                      │
│  [e] Edit  [d] Delete  [q] Quit                      │
│                                                      │
╰──────────────────────────────────────────────────────╯

💻 代码演示:进阶 CLAUDE.md 模板

# My SaaS Project

## Overview
B2B SaaS platform for HR management.
50K MAU, multi-tenant architecture.

## Tech Stack
- Frontend: Next.js 14 (App Router) + React 19
- Backend: tRPC + Prisma + PostgreSQL
- Auth: Clerk
- Payments: Stripe
- Deployment: Vercel + Supabase

## Commands
- `pnpm dev` — start all services
- `pnpm test` — run Vitest
- `pnpm test:e2e` — run Playwright
- `pnpm db:push` — push schema changes
- `pnpm db:seed` — seed test data

## Architecture Rules
- Use Server Components by default, 'use client' only when needed
- All API routes go through tRPC procedures
- Database queries MUST go through service layer (src/services/)
- Never import from `@prisma/client` directly, use `@/lib/db`

## Code Style
- 2-space indentation
- No semicolons
- Named exports only (no default exports)
- Use `type` imports: `import type { User } from '@/types'`
- Error messages in English, UI text supports i18n

## Git Workflow
- Branch naming: `feat/`, `fix/`, `chore/`
- Commit messages: Conventional Commits
- Always create PR, never push to main directly

## Testing
- Unit tests: colocate with source (*.test.ts)
- E2E tests: tests/e2e/
- Minimum 80% coverage for new code

## Important Context
- @README.md for project overview
- @docs/api-design.md for API conventions
- @.env.example for required environment variables

🔧 涉及的 Tools / 命令

工具/命令 作用
/init 自动生成 CLAUDE.md
/memory 查看/编辑自动记忆
@path/to/file 在 CLAUDE.md 中引入其他文件
.claude/rules/*.md 目录化规则(按功能拆分)
~/.claude/CLAUDE.md 全局个人偏好
CLAUDE.md 项目级指令

📝 本期要点回顾

  1. CLAUDE.md 是项目的 持久化上下文,每次会话自动加载
  2. /init 命令可以 一键生成 初始版本
  3. 使用 @文件路径 可以引入额外文件作为上下文
  4. Auto Memory 会自动保存你的偏好纠正
  5. 好的 CLAUDE.md 应该 具体明确:用 "2-space indentation" 而不是 "format properly"

🔗 参考资料