CLAUDE.md Usage Guide
CLAUDE.mdIt is the most important configuration file in Claude Code, used to pass project-level persistent instructions to Claude. Every time a Claude Code session is started, it automatically reads and loads the contents of this file, incorporating them into every conversation as system-level context.
In layman's terms,CLAUDE.mdit is a work manual you write for Claude in the project — telling it what the project is, what standards to follow, and what to be careful about, so that it can work in a way that meets project requirements every time, instead of being re-explained in every conversation.
The Role of CLAUDE.md
WithoutCLAUDE.mdit, Claude starts understanding your project from scratch every time, and you need to repeatedly tell it: which package manager to use, what the code style is, how to run tests, which files not to touch... WithCLAUDE.md, this information only needs to be written once, and Claude will follow it every time.
Specifically,CLAUDE.mdit can help you achieve the following:
- Unify team behavior: Commit the file to git, and all team members follow the same standards when using Claude Code
- Reduce repetitive communication: Project conventions, architecture rules, and prohibited items are written only once and remain effective permanently
- Reduce the probability of errors: Clearly inform Claude which operations are risky, preventing it from making wrong decisions
- Accelerate AI understanding: Help Claude quickly locate key files and understand the project structure, reducing unnecessary file exploration
File Placement Location
Claude Code loads from multiple locationsCLAUDE.md, and files in different locations have different scopes:
| Location | Path | Scope | Commit to git? |
|---|---|---|---|
| Project root directory | {项目根目录}/CLAUDE.md |
All sessions of the current project | ✅ Recommended to commit, shared by the team |
| Project local | {项目根目录}/.claude/CLAUDE.md |
All sessions of the current project | ❌ Add to .gitignore, for personal use only |
| Subdirectory | {任意子目录}/CLAUDE.md |
Automatically loaded when Claude opens files in that directory | ✅ Suitable for multi-module repositories |
| Global user-level | ~/.claude/CLAUDE.md |
All projects of the current user | ❌ Personal configuration, do not commit |
When multiple locations haveCLAUDE.md, Claude Code willload and merge all of them, with priority from high to low as follows:
Project local → Project root directory → Subdirectory → Global user level
The project root directory's
CLAUDE.mdIt is recommended to commit to git so the entire team shares the same set of AI working standards.Personal preferences (such as not liking semicolons) should be placed in
.claude/CLAUDE.mdand added to.gitignore, without affecting others.
Quickly Create CLAUDE.md
The simplest way is to let Claude Code automatically generate an initial version. After starting Claude Code in the project directory, run:
/init
Claude Code will analyze your project structure, code style, and existing configuration files (such aspackage.json、pyproject.toml、.eslintrcetc.), and automatically generate a version that matches the actual project situationCLAUDE.md, and then you can supplement and adjust based on it.
You can also create it manually in the project directory:
touch CLAUDE.md
File Content Structure
CLAUDE.mdIt is an ordinary Markdown file with no mandatory format requirements, but a good structure can help Claude find key information faster. The following is the recommended content structure:
# 项目名称 一句话说明这个项目是什么,方便 Claude 快速定位项目性质。 ## 技术栈 - 语言:Python 3.11 - 框架:FastAPI 0.110 - 数据库:PostgreSQL 15 + SQLAlchemy ORM - 测试:pytest ## 常用命令 ### 开发 ```bash uv run uvicorn main:app --reload # 启动开发服务器 uv run pytest # 运行所有测试 uv run pytest -k "test_auth" # 运行指定测试 ``` ### 代码检查 ```bash uv run ruff check . # 代码检查 uv run ruff format . # 代码格式化 ``` ## 项目结构 - `src/api/` — API 路由和请求处理 - `src/models/` — 数据库模型定义 - `src/services/` — 业务逻辑层 - `tests/` — 测试文件,与 src/ 目录结构镜像对应 ## 编码规范 - 使用 `uv` 管理依赖,不使用 pip 直接安装 - 所有函数必须有类型注解 - 字符串一律使用双引号 - 新增 API 路由必须同步添加测试 ## 注意事项 - 不要修改 `migrations/` 目录下的已有文件,只能新增迁移文件 - `config/secrets.py` 包含敏感配置,禁止输出其内容到日志或终端 - 数据库操作必须通过 Service 层,不要在路由层直接操作 ORM
Detailed Explanation of Core Content Modules
1. Common Commands
This isCLAUDE.mdMediumthe most frequently referencedpart. When Claude performs tasks such as testing, building, and code linting, it will first look for the commands defined here, avoiding guessing or using incorrect commands:
## 常用命令 ### 安装依赖 ```bash npm ci # 安装依赖(CI 环境使用,严格按 lock 文件安装) ``` ### 开发 ```bash npm run dev # 启动开发服务器(端口 3000) npm run build # 构建生产版本 npm run preview # 预览生产构建 ``` ### 测试 ```bash npm test # 运行所有测试 npm test -- --watch # 监听模式 npm test -- --coverage # 生成覆盖率报告 ``` ### 代码质量 ```bash npm run lint # ESLint 检查 npm run lint:fix # 自动修复可修复的问题 npm run typecheck # TypeScript 类型检查 ```
2. Project Structure Description
Helps Claude quickly locate files and reduce unnecessary directory scans, especially effective in large projects:
## 项目结构 ``` src/ ├── app/ # Next.js App Router 页面 │ ├── (auth)/ # 需要登录才能访问的页面组 │ └── api/ # API 路由 ├── components/ # 可复用 UI 组件 │ ├── ui/ # 基础 UI 组件(Button、Input 等) │ └── features/ # 业务组件(按功能模块组织) ├── lib/ # 工具函数和配置 │ ├── db/ # 数据库客户端和查询 │ └── auth/ # 认证相关逻辑 └── types/ # TypeScript 类型定义 ``` 关键文件: - `src/lib/db/client.ts` — 数据库连接配置 - `src/middleware.ts` — 认证中间件,处理路由保护 - `env.example` — 所有必要的环境变量示例
3. Coding Standards
Informs Claude of the project's code style and conventions, ensuring that generated code is consistent with the existing codebase style:
## 编码规范
### 通用
- 文件名使用 kebab-case(如 `user-profile.ts`),类名使用 PascalCase
- 优先使用具名导出(named export),避免默认导出(default export)
- 异步函数一律使用 async/await,禁止使用 .then() 链式调用
### 组件规范
- 组件文件与其测试文件放在同一目录(如 `Button.tsx` 和 `Button.test.tsx`)
- Props 类型使用 interface 定义,命名格式为 `${组件名}Props`
- 不要将业务逻辑写在组件中,提取为自定义 Hook 或 Service
### 错误处理
- API 路由使用统一的错误响应格式:`{ error: string, code: string }`
- 客户端错误通过 Error Boundary 捕获,不要在每个组件里单独 try/catch
4. Architecture Constraints and Prohibited Matters
This is the key part to prevent Claude from making "smart but wrong" decisions. For special situations that you understand but Claude does not know, you must clearly write them out:
## 架构约束 - 所有数据库查询必须通过 `src/lib/db/queries/` 中的函数执行,不要在路由或组件中直接写 SQL - 状态管理使用 Zustand,不要引入 Redux 或其他状态管理库 - 样式使用 Tailwind CSS utility class,不要新增 CSS 文件或使用 CSS Modules ## 注意事项(重要) - `legacy/` 目录下的代码是遗留代码,**禁止修改**,只能读取 - `.env.local` 和 `.env.production` 包含真实密钥,**禁止输出文件内容** - `prisma/migrations/` 中已有的迁移文件**禁止修改**,数据库变更只能新增迁移 - 修改 `src/middleware.ts` 前必须先告知我,该文件影响所有路由的认证逻辑
5. Development Environment Description
Helps Claude understand the project's runtime environment, avoiding command execution failures due to environment differences:
## 开发环境 - Node.js:需要 v20 或以上版本(通过 `.nvmrc` 指定) - 包管理器:pnpm(禁止使用 npm 或 yarn 安装依赖) - 本地数据库:Docker Compose 启动(`docker compose up -d`) - 端口:前端 3000,API 3001,数据库 5432 ### 环境变量 参考 `.env.example` 文件配置本地环境变量,复制为 `.env.local` 后填入实际值。 必填项:`DATABASE_URL`、`NEXTAUTH_SECRET`、`NEXTAUTH_URL`
Configuration for Multi-Module Repository (Monorepo)
In a monorepo, you can place a global one in the repository root directoryCLAUDE.md, and place the respective one in each sub-package directory.CLAUDE.mdWhen Claude opens a file in a sub-package, it will load both the root directory and the sub-package directory files:
my-monorepo/
├── CLAUDE.md ← 全局规范:共用命令、整体架构、通用约定
├── packages/
│ ├── web/
│ │ └── CLAUDE.md ← 前端专属:React 规范、样式约定、构建流程
│ ├── api/
│ │ └── CLAUDE.md ← 后端专属:API 设计规范、数据库约定
│ └── shared/
│ └── CLAUDE.md ← 共享包:导出规则、版本管理约定
└── tools/
└── CLAUDE.md ← 工具脚本:特殊说明和使用限制
<!-- 根目录 CLAUDE.md(全局规范) --> # My Monorepo 使用 pnpm workspace 管理的前后端一体化项目。 ## 全局命令 ```bash pnpm install # 安装所有包的依赖 pnpm -r build # 构建所有包 pnpm -r test # 运行所有包的测试 pnpm --filter web dev # 只启动 web 包的开发服务器 ``` ## 包之间的依赖关系 - `web` 和 `api` 都依赖 `shared` - 禁止 `shared` 依赖 `web` 或 `api`(防止循环依赖) - 跨包引用使用包名(如 `@my-app/shared`),不要使用相对路径
Referencing External Files with @ Syntax
When the project already has specification documents (such as API design specifications, database design documents, etc.), there is no need to copy the content intoCLAUDE.mdInstead, directly use@file pathto reference them.
When Claude readsCLAUDE.mdit will automatically load the referenced file contents:
## 规范文档 详细的 API 设计规范请参考: @docs/api-design-guide.md 数据库设计约定: @docs/database-conventions.md 组件库使用说明: @docs/component-guidelines.md
The referenced file path is relative to
CLAUDE.mdthe directory where the file is located. The referenced file content will occupy context window space, so avoid referencing overly large files (it is recommended that a single referenced file not exceed 500 lines).
Suggestions for Using Global CLAUDE.md
User-level~/.claude/CLAUDE.mdis suitable for storing personal preferences and habits that are common across projects; these contents take effect for all projects:
<!-- 文件路径:~/.claude/CLAUDE.md --> # 个人全局配置 ## 回答偏好 - 回复使用中文 - 代码修改前先简要说明修改思路,不要直接给出代码 - 遇到有多种实现方案时,列出选项让我选择,而不是直接选一种 ## 通用约定 - 提交信息使用英文,格式:`type(scope): description` - 新文件开头不加版权注释 - 优先使用原生 API,避免引入不必要的依赖 ## 安全习惯 - 修改认证相关代码前主动提示我注意安全影响 - 不要在代码注释或日志中输出任何密钥或 token
Maintenance Suggestions for CLAUDE.md
1. Keep It Concise
CLAUDE.mdThe content will occupy context window space in every session. Too much content will compress the actual context space available to Claude, reducing efficiency. It is recommended to follow these principles:
- Write each rule only once; do not repeat the same meaning.
- Do not include background information unrelated to code (such as company introductions, product plans).
- Information that can be conveyed through the code itself (such as eslint configuration already defining code style) does not need to be
CLAUDE.mddeclared again in the file. - It is recommended to keep the total word count within 500 words; when it exceeds 1000 words, consider simplifying.
2. Continuously Update
As the project evolves,CLAUDE.mdit also needs to be updated synchronously. The following occasions should trigger updates:
- Changed package manager or build tool
- Added or removed important dependency libraries
- Established new coding conventions
- Discovered that Claude repeatedly makes the same type of error (indicating that it needs to be
CLAUDE.mdsupplemented in the file) - A certain file or module has become unmodifiable at will (add it to the precautions)
3. Use Imperative Language
The clearer the instruction, the higher the probability that Claude will follow it. Avoid vague descriptions and use direct commands:
| ❌ Vague description | ✅ Clear instruction |
|---|---|
| Code should be relatively clean | Functions should not exceed 50 lines; if they do, they must be split. |
| Try to write tests | Every new function must have a corresponding unit test |
| Pay attention to safety | User input must pass throughsanitize()function processing before being passed into database queries |
| The legacy directory is not very important | It is forbidden to modifylegacy/any files in the directory |
| Using pnpm is better | For dependency management, use only pnpm; npm and yarn are prohibited. |
Complete Example
The following is a Node.js + TypeScript full-stack project'sCLAUDE.mdcomplete example, which can serve as a reference template for your project:
Example
Based on Next.js 14 App Router + Prisma +E-commerce management system with PostgreSQL.
## Tech Stack
-Frontend: Next.js 14(App Router)、TypeScript、Tailwind CSS、shadcn/ui
-Backend: Next.js API Routes、Prisma ORM
-Database: PostgreSQL15
-Auth: NextAuth.js v5
-Package manager: pnpm
## Common Commands
```bash
pnpm dev # Start the dev server (port3000)
pnpm build &&pnpm start # Build and start the production server
pnpm test # Run all tests
pnpm test:e2e # Run end-to-end tests (requires starting the dev server first)
pnpm db:migrate # Run database migrations
pnpm db:studio # Open Prisma Studio (database visualization tool)
pnpm lint &&pnpm typecheck # Code and type checking
```
## Project Structure
- `src/app/` — App Router pages and API routes
- `src/app/(dashboard)/` — Admin pages requiring login
- `src/app/api/` — API routes (RESTful style)
- `src/components/` — Reusable components
- `src/lib/` — Utility functions, database client, auth config
- `prisma/schema.prisma` — Database schema definitions
## Coding Standards
-Only use named exports (namedexport), default exports are prohibiteddefault export(except for Next.jspage files)
-Server components are async by default; client components add ` at the top of the file"use client"`
-API routes use a unified response format: success `{ data: T }`, failure `{ error: string, code: string }`
-Database queries are encapsulated in `src/lib/db/` directory; do not use the `prisma` client directly elsewhere
## Notes
- `prisma/migrations/Existing files in `**must not be modified**; database changes can only be made by running `pnpm db:migrate` to add new migrations
- `.env.local` contains real secrets,**Do not read or output file contents**
- `src/lib/auth.ts` is the core auth file,**you must inform me before modifying it**
-After modifying `prisma/schema.prisma`, you must run `pnpm db:migrate` and commit the migration files
Frequently Asked Questions
Q: What if Claude doesn't follow the rules in CLAUDE.md?
First, check whether the rule is stated clearly enough (see the "use imperative language" suggestion above). If it is already clear but still not followed, you can re-emphasize it in the specific conversation, or move the rule to an earlier position in the file—Claude pays more attention to the content in the first half of the file.
Q: Is a longer CLAUDE.md better?
No. Too much content has two downsides: first, it takes up context window space, reducing the room for Claude to handle actual tasks; second, important rules get buried in large amounts of text and are less likely to be followed. It is recommended to review periodically and remove entries that are no longer applicable or of low value.
Q: When is the CLAUDE.md in a subdirectory loaded?
When Claude opens or edits a file in that subdirectory, the subdirectory'sCLAUDE.mdis automatically loaded. You don't need to manually tell Claude to read it; the whole process is automatic.
Q: Can I reference another CLAUDE.md in CLAUDE.md?
You cannot reference it directly, but you can use@file pathsyntax to reference the content of any Markdown file. If there are conventions shared across modules, it is recommended to extract them into a separate document file, and then in eachCLAUDE.mduse@to reference it.