CLAUDE.md配置文件
用Claude Code时,每次都要解释项目信息、编码规范这些重复内容,很浪费时间。我之前就因为忘记说某个规范,Claude生成的代码完全不符合团队要求,改了半天才弄好。
CLAUDE.md配置文件就是解决这个问题的。
什么是CLAUDE.md
CLAUDE.md就是一个Markdown文件,Claude Code启动时会自动读取。相当于项目的"说明书",告诉Claude:
- 项目干嘛的
- 用了什么技术
- 目录结构
- 编码规范
- 常用命令
- 注意事项
配置文件的层级
Claude Code支持三层配置,优先级从高到低:
- 企业级 - 公司统一规范
- 项目级 (
./CLAUDE.md) - 团队共享 - 用户级 (
~/.claude/CLAUDE.md) - 个人设置
这样分层的好处:
- 用户级:个人偏好(语言、编码风格)
- 项目级:项目规则(技术栈、架构)
- 企业级:公司规范(安全策略)
为什么CLAUDE.md如此重要
对比:有无CLAUDE.md的差异
没有CLAUDE.md时:
你: 帮我创建一个API路由
Claude: 好的,我来创建一个路由文件。
[创建了basic-route.js]
你: 不对,我们项目用的是TypeScript,而且路由要放在src/routes目录下
Claude: 抱歉,让我重新创建。
[重新创建src/routes/basic-route.ts]
你: 还有,我们团队要求使用函数式组件,需要添加JSDoc注释
Claude: 明白了,我来修改。
[添加注释和调整代码风格]
你: 记得要导出类型定义...
Claude: 好的,我添加类型导出。
有CLAUDE.md后:
你: 帮我创建一个API路由
Claude: 我会按照项目规范创建TypeScript路由文件。
[直接创建src/routes/basic-route.ts,包含:
- TypeScript类型定义
- JSDoc注释
- 函数式组件
- 类型导出
- 符合团队编码规范]
✓ 一次到位
CLAUDE.md的核心价值
-
省时间
- 不用重复解释项目
- 规范自动遵守
- 技术栈已知
-
代码质量
- 风格统一
- 符合团队规范
- 少返工
-
开发效率
- 配置一次,长期有效
- 减少沟通
- 一次做对
-
知识传承
- 新人快速上手
- 最佳实践文档化
- 团队标准统一
创建你的第一个CLAUDE.md
自动生成配置
Claude Code提供了/init命令来自动生成CLAUDE.md文件:
# 在项目根目录启动Claude Code
claude
# 使用init命令
/init
Claude会自动分析你的项目:
- 扫描package.json、requirements.txt等配置文件
- 识别项目结构和目录
- 检测使用的框架和工具
- 生成定制化的CLAUDE.md
输出示例:
🔍 Analyzing your project...
✓ Detected: Node.js project with TypeScript
✓ Found: React + Next.js framework
✓ Identified: ESLint, Prettier configurations
✓ Discovered: 12 key directories
📝 Generating CLAUDE.md...
✓ CLAUDE.md created successfully!
The file includes:
- Project overview
- Technology stack
- Directory structure
- Common commands
- Coding conventions
手动创建配置
你也可以手动创建CLAUDE.md文件。以下是一个基础模板:
# Project: My Awesome App
## Overview
A modern web application built with React and TypeScript.
## Technology Stack
- Frontend: React 18, TypeScript, Tailwind CSS
- Build: Vite
- Testing: Jest, React Testing Library
- Linting: ESLint, Prettier
## Directory Structure
src/ ├── components/ # Reusable React components ├── pages/ # Page components ├── hooks/ # Custom React hooks ├── utils/ # Utility functions ├── types/ # TypeScript type definitions └── styles/ # Global styles
## Coding Conventions
- Use functional components with hooks
- TypeScript strict mode enabled
- Component files: PascalCase.tsx
- Utility files: camelCase.ts
- CSS modules for component styles
## Common Commands
```bash
npm run dev # Start development server
npm run build # Build for production
npm test # Run tests
npm run lint # Lint code
## CLAUDE.md的语法和结构
### 基本语法
CLAUDE.md使用标准Markdown语法,Claude可以理解所有Markdown元素:
```markdown
# 一级标题 - 项目名称
## 二级标题 - 主要章节
### 三级标题 - 子章节
**粗体** - 重要信息
*斜体* - 强调内容
`代码` - 命令或代码片段
- 无序列表
1. 有序列表
[链接](url)
```代码块```
推荐的文档结构
一个完善的CLAUDE.md通常包含以下部分:
# 项目名称
## 1. Project Overview
项目简介、目标、核心功能
## 2. Technology Stack
技术栈详细列表
## 3. Architecture
系统架 构、设计模式
## 4. Directory Structure
目录结构说明
## 5. Development Setup
开发环境配置
## 6. Coding Conventions
编码规范和最佳实践
## 7. Common Commands
常用命令清单
## 8. API Guidelines
API设计规范(如适用)
## 9. Testing Strategy
测试策略和要求
## 10. Deployment
部署流程和注意事项
## 11. Troubleshooting
常见问题和解决方案
实战配置示例
示例1: React + TypeScript前端项目
# E-commerce Frontend
## Project Overview
Modern e-commerce platform frontend built with React, TypeScript, and Next.js.
Focus on performance, accessibility, and user experience.
## Technology Stack
- **Framework**: Next.js 14 (App Router)
- **Language**: TypeScript 5.0+ (strict mode)
- **Styling**: Tailwind CSS + CSS Modules
- **State Management**: Zustand
- **Data Fetching**: TanStack Query (React Query)
- **Forms**: React Hook Form + Zod validation
- **Testing**: Vitest + React Testing Library
- **E2E Testing**: Playwright
## Architecture Patterns
- **Component Structure**: Atomic Design (atoms, molecules, organisms, templates, pages)
- **State**: Server state (React Query) + Client state (Zustand)
- **Routing**: File-based routing with Next.js App Router
- **API**: RESTful API with fetch wrapper
## Directory Structure
src/ ├── app/ # Next.js app directory │ ├── (auth)/ # Auth route group │ ├── (shop)/ # Shop route group │ └── api/ # API routes ├── components/ │ ├── atoms/ # Basic components (Button, Input) │ ├── molecules/ # Composite components (SearchBar) │ ├── organisms/ # Complex components (Header, ProductCard) │ └── templates/ # Page templates ├── hooks/ # Custom React hooks ├── lib/ # Utilities and configurations ├── stores/ # Zustand stores ├── types/ # TypeScript type definitions └── styles/ # Global styles
## Coding Conventions
### Component Guidelines
- **MUST** use functional components with TypeScript
- **MUST** define prop types with TypeScript interfaces
- **MUST** use named exports for components
- **PREFER** composition over inheritance
- **PREFER** custom hooks for reusable logic
Example:
```typescript
interface ButtonProps {
variant: 'primary' | 'secondary';
children: React.ReactNode;
onClick?: () => void;
}
export function Button({ variant, children, onClick }: ButtonProps) {
return (
<button className={styles[variant]} onClick={onClick}>
{children}
</button>
);
}
Naming Conventions
- Components: PascalCase (e.g.,
ProductCard.tsx) - Hooks: camelCase with 'use' prefix (e.g.,
useCart.ts) - Utils: camelCase (e.g.,
formatPrice.ts) - Types: PascalCase with 'Type' or 'Interface' (e.g.,
UserType.ts) - CSS Modules: camelCase (e.g.,
productCard.module.css)
Import Order
// 1. React and Next.js
import { useState } from 'react';
import Link from 'next/link';
// 2. External libraries
import { useQuery } from '@tanstack/react-query';
import clsx from 'clsx';
// 3. Internal modules
import { Button } from '@/components/atoms';
import { useCart } from '@/hooks';
// 4. Types
import type { Product } from '@/types';
// 5. Styles
import styles from './ProductCard.module.css';
State Management Rules
- Server state: Use React Query (no caching in Zustand)
- Client state: Use Zustand for global UI state
- Local state: Use useState for component-specific state
- Form state: Use React Hook Form
Common Commands
# Development
npm run dev # Start dev server (http://localhost:3000)
npm run build # Production build
npm run start # Start production server
# Testing
npm run test # Run unit tests
npm run test:watch # Watch mode
npm run test:e2e # Run Playwright E2E tests
npm run test:coverage # Generate coverage report
# Code Quality
npm run lint # ESLint
npm run format # Prettier
npm run type-check # TypeScript check
API Integration
- Base URL: Set in
.env.localasNEXT_PUBLIC_API_URL - Authentication: JWT token in Authorization header
- Error Handling: Use custom
ApiErrorclass - Request Wrapper: Use
lib/api.tsfetch wrapper
Example:
import { api } from '@/lib/api';
// GET request
const products = await api.get<Product[]>('/products');
// POST request with auth
const order = await api.post<Order>('/orders', orderData, {
auth: true
});
Testing Requirements
- Unit Tests: All utilities and hooks MUST have tests
- Component Tests: Complex components SHOULD have tests
- E2E Tests: Critical user flows MUST have E2E tests
- Coverage: Aim for >80% code coverage
Performance Guidelines
- Use Next.js Image component for all images
- Lazy load components below the fold
- Implement virtual scrolling for long lists
- Use React.memo() for expensive components
- Avoid unnecessary re-renders
Accessibility (a11y) Requirements
- All interactive elements MUST be keyboard accessible
- ARIA labels for icon buttons
- Semantic HTML elements
- Color contrast ratio >= 4.5:1
- Support screen readers
Common Pitfalls to Avoid
⚠️ DO NOT use any type in TypeScript
⚠️ DO NOT fetch data in components (use React Query)
⚠️ DO NOT use inline styles (use Tailwind or CSS modules)
⚠️ DO NOT commit .env.local file
⚠️ DO NOT skip TypeScript errors to "fix" issues
Useful Resources
### 示例2: Node.js + Express后端项目
```markdown
# E-commerce Backend API
## Project Overview
RESTful API backend for e-commerce platform built with Node.js, Express, and PostgreSQL.
Focuses on scalability, security, and maintainability.
## Technology Stack
- **Runtime**: Node.js 20 LTS
- **Framework**: Express 4.x
- **Language**: TypeScript 5.0+
- **Database**: PostgreSQL 15 + Prisma ORM
- **Validation**: Zod
- **Authentication**: JWT + bcrypt
- **Testing**: Jest + Supertest
- **Documentation**: Swagger/OpenAPI 3.0
## Architecture
- **Pattern**: Layered Architecture (Controller → Service → Repository)
- **Authentication**: JWT-based with refresh tokens
- **Authorization**: Role-based access control (RBAC)
- **Error Handling**: Centralized error handler middleware
- **Logging**: Winston with rotation
## Directory Structure
src/ ├── config/ # Configuration files ├── controllers/ # Request handlers ├── services/ # Business logic ├── repositories/ # Database access layer ├── models/ # Prisma models ├── middlewares/ # Express middlewares ├── routes/ # API routes ├── utils/ # Utility functions ├── types/ # TypeScript types ├── validators/ # Zod schemas └── tests/ # Test files
## Coding Conventions
### Layered Architecture
```typescript
// Controller - Handle HTTP request/response
export const createProduct: RequestHandler = async (req, res, next) => {
try {
const data = ProductCreateSchema.parse(req.body);
const product = await productService.create(data);
res.status(201).json({ success: true, data: product });
} catch (error) {
next(error);
}
};
// Service - Business logic
export const productService = {
async create(data: ProductCreateInput) {
// Validate business rules
await this.validateProductData(data);
// Call repository
return await productRepository.create(data);
}
};
// Repository - Database operations
export const productRepository = {
async create(data: ProductCreateInput) {
return await prisma.product.create({ data });
}
};
API Response Format
All API responses MUST follow this structure:
// Success Response
{
"success": true,
"data": { ... },
"message": "Optional success message"
}
// Error Response
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable message",
"details": { ... } // Optional
}
}
Naming Conventions
- Files: kebab-case (e.g.,
user-controller.ts) - Classes: PascalCase (e.g.,
UserService) - Functions: camelCase (e.g.,
getUserById) - Constants: UPPER_SNAKE_CASE (e.g.,
MAX_LOGIN_ATTEMPTS) - Database tables: snake_case (e.g.,
user_sessions)
Environment Variables
Required variables in .env:
# Server
NODE_ENV=development
PORT=3000
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
# JWT
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=15m
REFRESH_TOKEN_EXPIRES_IN=7d
# Redis (for sessions)
REDIS_URL=redis://localhost:6379
Common Commands
# Development
npm run dev # Start dev server with nodemon
npm run build # Build TypeScript
npm run start # Start production server
# Database
npx prisma migrate dev # Create migration
npx prisma generate # Generate Prisma Client
npx prisma studio # Open Prisma Studio
# Testing
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
# Code Quality
npm run lint # ESLint
npm run format # Prettier
npm run type-check # TypeScript check
API Design Guidelines
RESTful Conventions
GET /api/v1/products # List products
GET /api/v1/products/:id # Get single product
POST /api/v1/products # Create product
PATCH /api/v1/products/:id # Update product
DELETE /api/v1/products/:id # Delete product
Request Validation
MUST use Zod for all request validation:
import { z } from 'zod';
const ProductCreateSchema = z.object({
name: z.string().min(1).max(200),
price: z.number().positive(),
description: z.string().optional(),
categoryId: z.string().uuid()
});
// In controller
const data = ProductCreateSchema.parse(req.body);
Security Requirements
- MUST validate all user inputs
- MUST use parameterized queries (Prisma handles this)
- MUST hash passwords with bcrypt (min 10 rounds)
- MUST sanitize error messages (no stack traces in production)
- MUST implement rate limiting on authentication endpoints
- MUST use HTTPS in production
- MUST set secure HTTP headers (use helmet.js)
Error Handling Pattern
// Custom error classes
export class AppError extends Error {
constructor(
public statusCode: number,
public code: string,
message: string
) {
super(message);
}
}
// Usage
throw new AppError(404, 'PRODUCT_NOT_FOUND', 'Product not found');
// Global error handler middleware
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
success: false,
error: {
code: err.code,
message: err.message
}
});
}
// Handle other errors...
};
Testing Strategy
- Unit Tests: Services and utilities (>90% coverage)
- Integration Tests: API endpoints with test database
- E2E Tests: Critical flows (auth, checkout, etc.)
Example:
describe('POST /api/v1/products', () => {
it('should create a product', async () => {
const response = await request(app)
.post('/api/v1/products')
.set('Authorization', `Bearer ${authToken}`)
.send({
name: 'Test Product',
price: 99.99,
categoryId: testCategoryId
})
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data.name).toBe('Test Product');
});
});
Common Pitfalls
⚠️ DO NOT expose internal error details to clients
⚠️ DO NOT store sensitive data in logs
⚠️ DO NOT use SELECT * queries (specify fields in Prisma)
⚠️ DO NOT skip request validation
⚠️ DO NOT commit .env files
⚠️ DO NOT use any type in TypeScript
### 示例3: Python + Django全栈项目
```markdown
# Django Blog Platform
## Project Overview
Full-stack blog platform built with Django and Django REST Framework.
## Technology Stack
- **Framework**: Django 4.2 LTS
- **API**: Django REST Framework 3.14
- **Database**: PostgreSQL 15
- **Caching**: Redis
- **Task Queue**: Celery
- **Testing**: pytest + pytest-django
## Project Structure
project/ ├── apps/ │ ├── accounts/ # User management │ ├── blog/ # Blog posts │ ├── comments/ # Comments system │ └── api/ # API endpoints ├── config/ # Django settings ├── static/ # Static files ├── media/ # User uploads └── tests/ # Test files
## Coding Conventions
### Python Style
- Follow PEP 8 style guide
- Use Black for formatting (line length: 88)
- Use type hints for all functions
- Docstrings for all classes and public methods
Example:
```python
from typing import Optional
from django.db import models
class Post(models.Model):
"""Blog post model."""
title: models.CharField = models.CharField(max_length=200)
content: models.TextField = models.TextField()
author: models.ForeignKey = models.ForeignKey(
"accounts.User",
on_delete=models.CASCADE,
related_name="posts"
)
def get_excerpt(self, length: int = 100) -> str:
"""Return post excerpt."""
if len(self.content) <= length:
return self.content
return f"{self.content[:length]}..."
Django Conventions
- App names: plural (e.g.,
accounts,posts) - Model names: singular (e.g.,
User,Post) - View classes: end with
VieworViewSet - URL names: app_name + action (e.g.,
blog_post_list)
Common Commands
# Development
python manage.py runserver # Start dev server
python manage.py makemigrations # Create migrations
python manage.py migrate # Apply migrations
# Testing
pytest # Run tests
pytest --cov # With coverage
pytest -k test_name # Run specific test
# Shell
python manage.py shell_plus # Enhanced shell
API Design
- Use DRF ViewSets for CRUD operations
- Implement pagination (PageNumberPagination)
- Use serializers for validation
- Version APIs (e.g.,
/api/v1/)
Testing Requirements
- All views MUST have tests
- Models MUST have tests for custom methods
- API endpoints MUST have integration tests
- Aim for >85% code coverage
## 编码规范配置详解
### 格式化规范
```markdown
## Code Formatting
### Automatic Formatting
- **Tool**: Prettier
- **Line Length**: 100 characters
- **Indentation**: 2 spaces
- **Semicolons**: Required
- **Trailing Commas**: ES5
- **Quote Style**: Single quotes
- **Arrow Function Parentheses**: Always
Run `npm run format` before committing.
### ESLint Rules
- Extends: `['airbnb', 'plugin:@typescript-eslint/recommended']`
- No console.log in production code
- Prefer const over let
- No unused variables
- Require explicit return types