CLAUDE.md Usage Guide
CLAUDE.md It is the most important configuration file in Claude Code, used to convey project-level persistent instructions to Claude. Every time a Claude Code session starts, it automatically reads and loads the contents of this file as system-level context integrated into every conversation.
In simple terms,CLAUDE.md it's a work manual you write for Claude in your project — telling it what the project is, what conventions to follow, and what to watch out for, so it can work in a way that meets the project's requirements every time, rather than re-explaining in every conversation.
The role of CLAUDE.md
No CLAUDE.md Without it, Claude understands 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... With CLAUDE.md, this information only needs to be written once, and Claude will follow it every time.
Specifically,CLAUDE.md It can help you with the following:
- Unify team behavior: commit the file to git so all team members follow the same conventions when using Claude Code
- Reduce repetitive communication: project conventions, architecture rules, and prohibitions are written once and take effect permanently
- Lower the chance of errors: clearly tell Claude which operations are risky, avoiding wrong decisions
- Accelerate AI understanding: help Claude quickly locate key files and understand the project structure, reducing unnecessary file exploration
File placement
Claude Code loads from multiple locations CLAUDE.md, with files in different locations having different scopes:
| Position | Path | Scope | Whether to 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, personal use only |
| Subdirectory | {任意子目录}/CLAUDE.md |
Automatically loaded when Claude opens files in that directory | ✅ Suitable for multi-module repos |
| Global user level | ~/.claude/CLAUDE.md |
All projects of the current user | ❌ Personal config, not committed |
When multiple locations exist CLAUDE.md , Claude Code willload and merge them all, with priority from high to low as follows:
项目本地 → 项目根目录 → 子目录 → 全局用户级
The project root's
CLAUDE.mdIt's recommended to commit to git so the whole team shares the same set of AI work conventions.Personal preferences (such as disliking semicolons) go in
.claude/CLAUDE.mdand add to.gitignore, without affecting others.
Quickly create CLAUDE.md
The easiest way is to have Claude Code auto-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 config files (such as package.json、pyproject.toml、.eslintrc ), and automatically generate a file tailored to the actual project — CLAUDE.md— which you can then build on and adjust.
You can also create it manually in the project directory:
touch CLAUDE.md
File content structure
CLAUDE.md It is an ordinary Markdown file with no mandatory format requirements, but a good structure helps Claude find key information faster. The following is a recommended content structure:
# 项目名称
一句话说明这个项目是什么,方便 Claude 快速定位项目性质。
## 技术栈
- 语言:Python 3.11
- 框架:FastAPI 0.110
- 数据库:PostgreSQL 15 + SQLAlchemy ORM
- 测试:pytest
## Common Commands
### 开发
```bash
uv run uvicorn main:app --reload # 启动开发服务器
uv run pytest # 运行所有测试
uv run pytest -k "test_auth" # 运行指定测试
Code checks
uv run ruff check . # 代码检查
uv run ruff format . # 代码格式化
Project Structure
src/api/— API routes and request handlingsrc/models/— Database model definitionssrc/services/— Business logic layertests/— Test files, mirroring the src/ directory structure
Coding standards
- Use
uvManage dependencies; do not install directly with pip - All functions must have type annotations
- Always use double quotes for strings
- New API routes must have tests added at the same time
Notes
- Do not modify
migrations/existing files in the directory; only add migration files config/secrets.pyContains sensitive configuration; never output its contents to logs or the terminal- Database operations must go through the Service layer; do not manipulate the ORM directly in the route layer
---
## Detailed explanation of core content modules
### 1、Common Commands
This is the most frequently referenced section in `CLAUDE.md`. When Claude performs tasks such as testing, building, or code checking, it prioritizes looking up the commands defined here to avoid guessing or using incorrect commands:
Common Commands
Install dependencies
npm ci # 安装依赖(CI 环境使用,严格按 lock 文件安装)
Development
npm run dev # 启动开发服务器(端口 3000)
npm run build # 构建生产版本
npm run preview # 预览生产构建
Testing
npm test # 运行所有测试
npm test -- --watch # 监听模式
npm test -- --coverage # 生成覆盖率报告
Code quality
npm run lint # ESLint 检查
npm run lint:fix # 自动修复可修复的问题
npm run typecheck # TypeScript 类型检查
### 2. Project Structure Description
Help Claude quickly locate files, reduce unnecessary directory scanning, especially effective in large projects:
Project Structure
src/
├── app/ # Next.js App Router 页面
│ ├── (auth)/ # 需要登录才能访问的页面组
│ └── api/ # API 路由
├── components/ # 可复用 UI 组件
│ ├── ui/ # 基础 UI 组件(Button、Input 等)
│ └── features/ # 业务组件(按功能模块组织)
├── lib/ # 工具函数和配置
│ ├── db/ # 数据库客户端和查询
│ └── auth/ # 认证相关逻辑
└── types/ # TypeScript 类型定义
Key files:
src/lib/db/client.ts— Database connection configurationsrc/middleware.ts— Authentication middleware, handles route protectionenv.example— Examples of all necessary environment variables
### 3、Coding Standards
Inform Claude about the project's coding style and conventions, ensuring that the generated code is consistent with the existing codebase style:
Coding standards
Universal
- Use kebab-case for filenames (such as
user-profile.ts), and PascalCase for class names - Prefer named exports and avoid default exports
- Always use async/await for async functions; do not use .then() chaining
Component conventions
- Put component files and their test files in the same directory (such as
Button.tsxandButton.test.tsx) - Define Props types using interface, with the naming format
${组件名}Props - Don't write business logic in components; extract it into custom Hooks or Services
Error handling
- API routes use a unified error response format:
{ error: string, code: string } - Catch client-side errors via Error Boundary; don't use individual try/catch in every component
### 4, Architectural Constraints and Prohibited Items
This is a crucial part to prevent Claude from making "smart but wrong" decisions. For special cases that you understand but Claude does not, you must explicitly write them out:
Architecture constraints
- All database queries must go through
src/lib/db/queries/the functions in ... to execute; do not write SQL directly in routes or components - Use Zustand for state management; do not introduce Redux or other state management libraries
- Use Tailwind CSS utility classes for styling; do not add new CSS files or use CSS Modules
Notes (Important)
legacy/The code under the ... directory is legacy code,do not modify it; you may only read it.env.localand.env.productioncontains real secrets,do not output the file contentsprisma/migrations/existing migration files in ...do not modify it; database changes may only add new migrations- Modify
src/middleware.tsbefore ... you must inform me first; this file affects the authentication logic of all routes
### 5. Development Environment Description
Help Claude understand the project's running environment to avoid command execution failures due to environmental differences:
Development environment
- Node.js: requires v20 or higher (specified via
.nvmrc) - Package manager: pnpm (do not use npm or yarn to install dependencies)
- Local database: started with Docker Compose (
docker compose up -d) - Ports: frontend 3000, API 3001, database 5432
Environment Variables
Reference .env.example configure local environment variables via the ... file, copy it to .env.local then fill in the actual values. Required fields:DATABASE_URL、NEXTAUTH_SECRET、NEXTAUTH_URL
---
## Configuration methods for a multi-module repository (Monorepo)
In a Monorepo, you can place a global `CLAUDE.md` in the repository root, and individual `CLAUDE.md` files in each subpackage directory. When Claude opens a file in a specific subpackage, it will load both the file from the root directory and the file from that subpackage directory:
my-monorepo/ ├── CLAUDE.md ← Global rules: shared commands, overall architecture, general conventions ├── packages/ │ ├── web/ │ │ └── CLAUDE.md ← Frontend-specific: React conventions, styling conventions, build process │ ├── api/ │ │ └── CLAUDE.md ← Backend-specific: API design conventions, database conventions │ └── shared/ │ └── CLAUDE.md ← Shared package: export rules, version management conventions └── tools/ └── CLAUDE.md ← Tool scripts: special notes and usage restrictions
My Monorepo
An integrated frontend-and-backend project managed with pnpm workspace.
Global commands
pnpm install # 安装所有包的依赖
pnpm -r build # 构建所有包
pnpm -r test # 运行所有包的测试
pnpm --filter web dev # 只启动 web 包的开发服务器
Dependencies between packages
webandapiall depend onshared- Forbid
sharedDepends onweborapi(to prevent circular dependencies) - Use package names for cross-package references (e.g.
@my-app/shared), do not use relative paths
---
## Use @ syntax to reference external files
当项目已经有了规范文档(如 API 设计规范、数据库设计文档等),不需要将内容复制到 `CLAUDE.md` 中,直接用 `@文件路径` 引用即可。
When Claude reads CLAUDE.md, it automatically loads the content of referenced files:
Specification documents
For detailed API design specifications, please refer to: @docs/api-design-guide.md
Database design conventions: @docs/database-conventions.md
Component library usage guide: @docs/component-guidelines.md
> 引用的文件路径是相对于 CLAUDE.md 所在目录的相对路径。引用的文件内容会占用上下文窗口,避免引用过大的文件(建议单个引用文件不超过 500 行)。
---
## Usage guidelines for global CLAUDE.md
The user-level ~/.claude/CLAUDE.md is suitable for storing personal preferences and habits common across projects; these contents apply to all projects:
Personal global configuration
Response preferences
- Respond in Chinese
- Before modifying code, briefly explain the approach first; do not give the code directly
- When there are multiple implementation options, list them for me to choose rather than picking one directly
General conventions
- Use English for commit messages, format:
type(scope): description - Do not add copyright headers at the top of new files
- Prefer native APIs and avoid introducing unnecessary dependencies
Security practices
- Proactively alert me to security implications before modifying authentication-related code
- Do not output any secrets or tokens in code comments or logs
---
## Maintenance Suggestions for CLAUDE.md
### 1、保持精简
The content of `CLAUDE.md` will occupy the context window in every session. Too much content will compress the actual context space available to Claude, thus reducing efficiency. It is recommended to follow the following principles:
- 每条规则只写一次,不要重复表达相同意思
- 与代码无关的背景信息(如公司介绍、产品规划)不要写进来
- 能通过代码本身传达的信息(如 eslint 配置已经定义了代码风格),不需要在 `CLAUDE.md` 中重复声明
- 建议总字数控制在 500 字以内,超过 1000 字时需要考虑精简
### 2、持续更新
As the project evolves, `CLAUDE.md` also needs to be updated synchronously. The following occasions should trigger an update:
- 更换了包管理器或构建工具
- 添加或移除了重要的依赖库
- 制定了新的编码约定
- 发现 Claude 反复犯同一类错误(说明需要在 `CLAUDE.md` 中补充说明)
- 某个文件或模块变得不能随意修改(增加到注意事项中)
### 3、Using imperative language
The clearer the instruction, the higher the probability that Claude will comply. Avoid vague descriptions and use direct commands:
| ❌ 模糊描述 | ✅ 明确指令 |
| --- | --- |
| 代码应该比较整洁 | 函数不超过 50 行,超过时必须拆分 |
| 尽量写测试 | 每个新增函数都必须有对应的单元测试 |
| 注意安全 | 用户输入必须通过 `sanitize()` 函数处理后才能传入数据库查询 |
| legacy 目录不太重要 | 禁止修改 `legacy/` 目录下的任何文件 |
| 用 pnpm 比较好 | 依赖管理只使用 pnpm,禁止使用 npm 或 yarn |
---
## Complete Example
The following is a complete example of a `CLAUDE.md` for a Node.js + TypeScript full-stack project, which can serve as a reference template for your project:
## 实例
# MyApp — E-commerce Management Backend
基于 Next.
js
14
App Router
+
Prisma
+
PostgreSQL 的电商管理系统。
## 技术栈
-
前端:Next.
js
14
(App Router)、TypeScript、Tailwind CSS、shadcn
/
ui
-
后端:Next.
js
API Routes、Prisma ORM
-
数据库:PostgreSQL
15
-
认证:NextAuth.
js
v5
-
包管理:pnpm
## Common Commands
```bash
pnpm dev # 启动开发服务器(端口
3000
)
pnpm build
&&
pnpm start # 构建并启动生产服务器
pnpm test # 运行所有测试
pnpm test
:
e2e # 运行端到端测试(需先启动 dev server)
pnpm db
:
migrate # 执行数据库迁移
pnpm db
:
studio # 打开 Prisma Studio(数据库可视化工具)
pnpm lint
&&
pnpm typecheck # 代码检查和类型检查
Project Structure
`src
/
app
/
` — App Router pages and API routes
`src
/
app
/
(
dashboard
)
/
` — admin pages that require login
`src
/
app
/
api
/
` — API routes (RESTful style)
`src
/
components
/
` — reusable components
`src
/
lib
/
` — utility functions, database client, authentication configuration
`prisma
/
schema.
prisma
` — database schema definitions
Coding standards
Use only named exports (named
export
), prohibit
default
export
(except Next.
js
page files)
Server components are async by default; add ` at the top of client component files
"use client"
`
Unified return format for API routes: success `
{
data
:
T
}
,失败
{
error
:
string
,
code
:
string
}
`
Database queries are encapsulated in the `src
/
lib
/
db
/
目录下,不在其他地方直接使用prisma` client
Notes
`prisma
/
migrations
/
` existing files in
**
do not modify it
**
; database changes may only run `pnpm db
:
migrate` to add new migrations
`.
env
.
local
` contains real secrets,
**
do not read or output the file contents
**
`src
/
lib
/
auth.
ts
` is the core authentication file,
**
you must inform me before modifying it
**
Modify `prisma
/
schema.
prisma
后必须执行pnpm db
:
migrate` and commit the migration files
Common questions
Q: What should I do if Claude does not follow the rules in CLAUDE.md?
First, check whether the rules are phrased clearly enough (see the "use imperative language" suggestion above). If the wording is already clear but Claude still does not comply, 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 first half of a file.
Q: Is a longer CLAUDE.md better?
No. Having too much content has two side effects: first, it occupies the context window, reducing the space Claude has to handle actual tasks; second, important rules get buried in a mass of text and are actually less likely to be followed. It is recommended to review regularly and delete entries that are no longer applicable or of low value.
Q: When is a CLAUDE.md in a subdirectory loaded?
When Claude opens or edits a file in that subdirectory, that subdirectory's CLAUDE.md is automatically loaded. You do not need to manually tell Claude to read it; the whole process is automatic.
Q: Can you reference another CLAUDE.md from within a CLAUDE.md?
You cannot reference it directly, but you can use the @文件路径 syntax to reference the contents of any Markdown file. If there are specifications shared across modules, it is recommended to extract them into a separate documentation file, and then in each CLAUDE.md use @ to reference it.