Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CLAUDE.md Usage Guide

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:


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.md It'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.md and 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

Coding standards

Notes



---



## 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:



### 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

Component conventions

Error handling



### 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

Notes (Important)



### 5. Development Environment Description



Help Claude understand the project's running environment to avoid command execution failures due to environmental differences:



Development environment

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



---



## 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

General conventions

Security practices



---



## 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.