项目配置最佳实践
配置做得好,Claude Code用起来顺手。配置不好,Claude老是误解你的意思,生成一堆不合规范的代码,甚至引入安全漏洞。
下面聊聊怎么配置项目,让Claude Code真正成为你的得力助手。
为什么要重视配置
配置不好的代价
没配置CLAUDE.md:
你: 创建一个用户列表组件
Claude: [创建了 UserList.js]
- 用了类组件(项目已经全面迁移函数式组件)
- 文件名驼峰命名(项目要求kebab-case)
- inline样式(项目要求CSS Modules)
- 没TypeScript类型(项目是TS)
你: 不对不对,都不符合规范...[开始返工]
返工: 15分钟
配置完善后:
你: 创建一个用户列表组件
Claude: [创建了 user-list.tsx]
✓ 函数式组件 + TypeScript
✓ kebab-case命名
✓ CSS Modules
✓ 完整类型定义
✓ 符合项目规范
✓ 包含测试框架
一次到位,不用改
省了15分钟 + 避免错误
数据说话:
| 配置情况 | 效率提升 | 错误减少 | 一次对率 |
|---|---|---|---|
| 基础配置 | 40% | 60% | 75% |
| 完整配置 | 70% | 85% | 95% |
| 没配置 | 0% | 0% | 30% |
CLAUDE.md完整模板
企业级完整模板
这是一个适用于中大型项目的CLAUDE.md完整模板,涵盖所有关键配置项:
# 项目名称: [Your Project Name]
## 项目概述
[1-2句话描述项目的核心功能和目标]
- **项目类型**: [Web应用/移动应用/桌面应用/API服务等]
- **主要用户**: [目标用户群体]
- **核心价值**: [项目解决的核心问题]
- **当前状态**: [开发中/生产环境/维护模式]
## 技术栈
### 核心框架
- **前端**: [框架名称] [版本]
- **后端**: [框架名称] [版本]
- **数据库**: [数据库类型] [版本]
- **运行时**: [Node.js/Python/Java等] [版本要求]
### 开发工具
- **语言**: [TypeScript/JavaScript/Python等] [版本]
- **构建工具**: [Vite/Webpack/Parcel等]
- **包管理器**: [npm/yarn/pnpm]
- **版本控制**: Git
- **CI/CD**: [GitHub Actions/GitLab CI等]
### 依赖管理
```json
// package.json关键依赖示例
{
"dependencies": {
"react": "^18.2.0",
"typescript": "^5.0.0"
}
}
项目架构
架构模式
- 设计模式: [MVC/微服务/分层架构/单体架构等]
- 目录组织: [功能模块/技术分层/混合方式]
目录结构
project-root/
├── src/ # 源代码目录
│ ├── components/ # [说明]
│ ├── pages/ # [说明]
│ ├── hooks/ # [说明]
│ ├── utils/ # [说明]
│ ├── services/ # [说明]
│ └── types/ # [说明]
├── tests/ # 测试目录
├── docs/ # 文档目录
├── config/ # 配置文件
└── scripts/ # 构建和部署脚本
模块划分
- 模块A: [职责和边界]
- 模块B: [职责和边界]
- 共享模块: [哪些是共享的]
编码规范
命名约定
文件命名
- 组件文件:
PascalCase.tsx(如UserProfile.tsx) - 工具文件:
kebab-case.ts(如format-date.ts) - 样式文件:
*.module.css(如UserProfile.module.css) - 测试文件:
*.test.ts(如utils.test.ts)
代码命名
// 类和接口: PascalCase
class UserService {}
interface UserProfile {}
// 函数和变量: camelCase
function getUserData() {}
const userName = 'John';
// 常量: UPPER_SNAKE_CASE
const MAX_RETRY_COUNT = 3;
// 私有成员: _prefix
private _internalState = {};
// TypeScript类型: PascalCase + Type/Interface后缀
type UserType = {};
interface UserConfig {}
代码风格
TypeScript配置
- 严格模式: 必须启用
strict: true - 类型标注: 所有函数必须有返回类型
- 禁止使用:
any类型(使用unknown代替) - Null处理: 启用
strictNullChecks
代码格式
// 1. 导入顺序
// 1.1 React/框架核心
import { useState, useEffect } from 'react';
// 1.2 第三方库
import axios from 'axios';
import clsx from 'clsx';
// 1.3 内部模块(使用路径别名)
import { Button } from '@/components/atoms';
import { useAuth } from '@/hooks';
// 1.4 类型导入
import type { User } from '@/types';
// 1.5 样式文件
import styles from './UserProfile.module.css';
// 2. 组件定义
export function UserProfile({ userId }: UserProfileProps) {
// 2.1 Hooks(按顺序: state -> effect -> context -> custom)
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
// effect logic
}, [userId]);
// 2.2 派生状态
const isAdmin = user?.role === 'admin';
// 2.3 事件处理函数
const handleSave = () => {
// logic
};
// 2.4 渲染
return (
<div className={styles.container}>
{/* JSX */}
</div>
);
}
ESLint规则
{
"rules": {
"no-console": "warn",
"no-debugger": "error",
"prefer-const": "error",
"no-var": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": "warn"
}
}
注释规范
/**
* 用户服务类
* 负责用户相关的业务逻辑和数据操作
*/
export class UserService {
/**
* 根据用户ID获取用户信息
* @param userId - 用户ID,必须是有效的UUID格式
* @returns 返回用户对象,如果用户不存在则返回null
* @throws {InvalidUserIdError} 当userId格式无效时抛出
* @example
* ```typescript
* const user = await userService.getById('123e4567-e89b-12d3-a456-426614174000');
* ```
*/
async getById(userId: string): Promise<User | null> {
// 实现逻辑
}
}
开发工作流
常用命令
开发命令
# 安装依赖
npm install
# 启动开发服务器
npm run dev # http://localhost:3000
# 构建生产版本
npm run build
# 本地预览生产构建
npm run preview
# 代码检查
npm run lint # ESLint检查
npm run format # Prettier格式化
npm run type-check # TypeScript类型检查
测试命令
# 运行所有测试
npm test
# 运行测试并生成覆盖率报告
npm run test:coverage
# 监听模式(开发时使用)
npm run test:watch
# 运行E2E测试
npm run test:e2e
数据库命令
# 数据库迁移
npm run db:migrate # 执行迁移
npm run db:rollback # 回滚迁移
npm run db:seed # 填充种子数据
# 数据库客户端
npm run db:studio # 打开数据库管理界面
Git命令
# 提交前检查
npm run prepare # Husky钩子,自动运行lint和test
# 代码提交(使用Commitlint)
git commit # 交互式提交,遵循约定式提交规范
分支策略
main # 生产分支,受保护
├── develop # 开发分支
├── feature/* # 功能分支
├── bugfix/* # 修复分支
└── hotfix/* # 紧急修复分支
分支命名规范:
- 功能开发:
feature/feature-name - Bug修复:
bugfix/bug-description - 紧急修复:
hotfix/critical-fix - 重构:
refactor/component-name - 文档:
docs/document-name
提交规范
遵循约定式提交:
<type>(<scope>): <subject>
<body>
<footer>
Type类型:
feat: 新功能fix: Bug修复docs: 文档更新style: 代码格式(不影响代码运行)refactor: 重构perf: 性能优化test: 测试相关chore: 构建/工具链相关
示例:
feat(auth): add OAuth2 login with Google
Implement OAuth2 authentication flow:
- Add Google OAuth provider
- Implement token refresh mechanism
- Add user profile synchronization
Closes #123
环境配置
环境变量
必需变量
# .env.example (提交到Git)
# 应用配置
NODE_ENV=development
PORT=3000
APP_URL=http://localhost:3000
# 数据库
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
REDIS_URL=redis://localhost:6379
# API密钥
API_SECRET_KEY=your-secret-key-here
JWT_SECRET=your-jwt-secret
JWT_EXPIRES_IN=15m
# 第三方服务
STRIPE_API_KEY=sk_test_xxx
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
# 开发工具
DEBUG=true
LOG_LEVEL=debug
环境配置
// config/env.ts
export const config = {
port: parseInt(process.env.PORT || '3000', 10),
nodeEnv: process.env.NODE_ENV || 'development',
database: {
url: process.env.DATABASE_URL!,
},
jwt: {
secret: process.env.JWT_SECRET!,
expiresIn: process.env.JWT_EXPIRES_IN || '15m',
},
isDevelopment: process.env.NODE_ENV !== 'production',
isProduction: process.env.NODE_ENV === 'production',
} as const;
// 运行时验证
if (!config.database.url) {
throw new Error('DATABASE_URL environment variable is required');
}
多环境管理
env/
├── .env.example # 模板(提交)
├── .env.development # 开发环境(本地,不提交)
├── .env.staging # 预发布环境(部署时注入)
└── .env.production # 生产环境(部署时注入)
Git忽略配置:
# .gitignore
.env
.env.local
.env.*.local
*.env
API设计规范
RESTful API约定
GET /api/v1/resources # 列表
GET /api/v1/resources/:id # 详情
POST /api/v1/resources # 创建
PUT /api/v1/resources/:id # 完整更新
PATCH /api/v1/resources/:id # 部分更新
DELETE /api/v1/resources/:id # 删除
响应格式
成功响应:
{
"success": true,
"data": {
"id": "123",
"name": "Resource Name"
},
"message": "操作成功",
"meta": {
"timestamp": "2025-01-15T10:30:00Z",
"version": "1.0.0"
}
}
错误响应:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "请求参数验证失败",
"details": [
{
"field": "email",
"message": "邮箱格式不正确"
}
]
},
"meta": {
"timestamp": "2025-01-15T10:30:00Z",
"requestId": "req_abc123"
}
}
API版本控制
// 通过URL路径版本化
// api/v1/users
// api/v2/users
// 或通过Header版本化
// Accept: application/vnd.api+json; version=1
测试策略
测试金字塔
/\
/ \ E2E测试 (10%)
/____\ - 关键用户流程
/ \ - 使用Playwright/Cypress
/ \ - 集成测试 (30%)
/ \ - API测试
/____________\ - 组件集成
/ \ - 单元测试 (60% - 优先)
/ \ - 函数/类/组件单元测试
测试规范
// 单元测试示例
describe('UserService', () => {
describe('getById', () => {
it('should return user when valid id is provided', async () => {
// Arrange
const userId = '123';
const expectedUser = { id: userId, name: 'John' };
jest.spyOn(userRepository, 'findById').mockResolvedValue(expectedUser);
// Act
const result = await userService.getById(userId);
// Assert
expect(result).toEqual(expectedUser);
});
it('should return null when user not found', async () => {
// Arrange
const userId = '999';
jest.spyOn(userRepository, 'findById').mockResolvedValue(null);
// Act
const result = await userService.getById(userId);
// Assert
expect(result).toBeNull();
});
});
});
测试覆盖率要求
- 整体覆盖率: >= 80%
- 核心业务逻辑: >= 90%
- 工具函数: 100%
- 组件测试: >= 70%
安全规范
认证和授权
// JWT认证中间件
export async function authMiddleware(req: Request, res: Response, next: NextFunction) {
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token) {
return res.status(401).json({
success: false,
error: { code: 'UNAUTHORIZED', message: '缺少认证令牌' }
});
}
try {
const decoded = jwt.verify(token, config.jwt.secret);
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({
success: false,
error: { code: 'INVALID_TOKEN', message: '令牌无效或已过期' }
});
}
}
数据验证
import { z } from 'zod';
// 请求验证schema
export const CreateUserSchema = z.object({
email: z.string().email('邮箱格式不正确'),
password: z.string().min(8, '密码至少8位'),
name: z.string().min(2, '姓名至少2个字符'),
age: z.number().min(18, '必须年满18岁').optional(),
});
// 在Controller中使用
export async function createUser(req: Request, res: Response) {
try {
const validatedData = CreateUserSchema.parse(req.body);
// 处理逻辑
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({
success: false,
error: {
code: 'VALIDATION_ERROR',
message: '请求参数验证失败',
details: error.errors
}
});
}
}
}
安全清单
- ✅ 所有用户输入必须验证
- ✅ 敏感数据必须加密存储(密码使用bcrypt,成本因子>=10)
- ✅ 使用参数化查询,防止SQL注入
- ✅ 实施CORS策略
- ✅ 设置安全HTTP头(使用helmet.js)
- ✅ 实施速率限制(rate limiting)
- ✅ 生产环境禁用错误堆栈输出
- ✅ 定期更新依赖,修复安全漏洞
- ✅ 使用HTTPS(生产环境)
- ✅ 实施内容安全策略(CSP)
性能优化
前端性能
// 1. 代码分割
import { lazy, Suspense } from 'react';
const UserProfile = lazy(() => import('./UserProfile'));
function App() {
return (
<Suspense fallback={<Loading />}>
<UserProfile />
</Suspense>
);
}
// 2. 图片优化
import Image from 'next/image';
<Image
src="/avatar.jpg"
alt="用户头像"
width={100}
height={100}
loading="lazy"
/>
// 3. 防抖和节流
import { debounce } from 'lodash';
const handleSearch = debounce((query: string) => {
// 搜索逻辑
}, 300);
后端性能
// 1. 数据库查询优化
// ❌ 不好:N+1查询
const users = await User.findAll();
for (const user of users) {
user.posts = await Post.findAll({ where: { userId: user.id } });
}
// ✅ 好:预加载关联数据
const users = await User.findAll({
include: [{ model: Post, as: 'posts' }]
});
// 2. 缓存策略
import Redis from 'ioredis';
const redis = new Redis();
export async function getUserById(userId: string) {
const cacheKey = `user:${userId}`;
// 先查缓存
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// 查数据库
const user = await User.findById(userId);
// 写入缓存(5分钟过期)
await redis.setex(cacheKey, 300, JSON.stringify(user));
return user;
}
错误处理
错误分类
// 自定义错误类
export class AppError extends Error {
constructor(
public statusCode: number,
public code: string,
message: string,
public isOperational = true
) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
export class ValidationError extends AppError {
constructor(message: string) {
super(400, 'VALIDATION_ERROR', message);
}
}
export class NotFoundError extends AppError {
constructor(resource: string) {
super(404, 'NOT_FOUND', `${resource}不存在`);
}
}
// 全局错误处理中间件
export function errorHandler(
err: Error,
req: Request,
res: ExpressResponse,
next: NextFunction
) {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
success: false,
error: {
code: err.code,
message: err.message
}
});
}
// 未知错误
console.error('Unexpected error:', err);
return res.status(500).json({
success: false,
error: {
code: 'INTERNAL_ERROR',
message: '服务器内部错误'
}
});
}
日志规范
import winston from 'winston';
export const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// 使用示例
logger.info('User logged in', { userId: user.id, ip: req.ip });
logger.error('Database connection failed', { error: err.message });
logger.warn('High memory usage', { usage: '90%' });
Git配置最佳实践
.gitignore规范
# ============ 依赖 ============
node_modules/
.pnp
.pnp.js
# ============ 构建输出 ============
dist/
build/
out/
.next/
# ============ 环境变量 ============
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# ============ 日志 ============
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# ============ 测试覆盖率 ============
coverage/
.nyc_output/
# ============ IDE和编辑器 ============
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# ============ 临时文件 ============
*.tmp
.cache/
.temp/
# ============ 操作系统 ============
Thumbs.db
.DS_Store
# ============ 数据库 ============
*.sqlite
*.db
# ============ 其他 ============
debug.log
Git Hooks配置
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-push": "npm test"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write",
"git add"
],
"*.{json,md}": [
"prettier --write",
"git add"
]
}
}
文档规范
代码文档
/**
* 用户管理服务
*
* @module UserService
* @description 提供用户CRUD操作、认证、权限管理等核心功能
*
* @example
* ```typescript
* import { UserService } from '@/services/UserService';
*
* const userService = new UserService();
* const user = await userService.createUser({
* email: 'user@example.com',
* password: 'securepass123'
* });
* ```
*/
export class UserService {
/**
* 创建新用户
*
* @param {CreateUserDto} data - 用户数据
* @param {string} data.email - 用户邮箱(必须唯一)
* @param {string} data.password - 用户密码(将被加密存储)
* @param {string} data.name - 用户姓名
* @returns {Promise<User>} 创建的用户对象
* @throws {DuplicateEmailError} 当邮箱已存在时抛出
* @throws {ValidationError} 当数据验证失败时抛出
*
* @example
* ```typescript
* const user = await userService.createUser({
* email: 'john@example.com',
* password: 'MySecurePass123!',
* name: 'John Doe'
* });
* ```
*/
async createUser(data: CreateUserDto): Promise<User> {
// 实现
}
}
README规范
# 项目名称
简短描述项目的主要功能和价值(一句话)
## 功能特性
- ✅ 功能点1
- ✅ 功能点2
- ✅ 功能点3
## 技术栈
- **框架**: [框架名称]
- **语言**: [语言]
- **数据库**: [数据库]
- **部署**: [部署平台]
## 快速开始
### 环境要求
- Node.js >= 16.14.0
- npm >= 8.0.0
### 安装
\`\`\`bash
git clone https://github.com/user/repo.git
cd repo
npm install
\`\`\`
### 运行
\`\`\`bash
# 开发模式
npm run dev
# 生产构建
npm run build
npm start
\`\`\`
## 项目结构
\`\`\`
src/
├── components/ # React组件
├── pages/ # 页面组件
└── utils/ # 工具函数
\`\`\`
## 贡献指南
欢迎贡献!请查看 [CONTRIBUTING.md](CONTRIBUTING.md)
## 许可证
MIT
禁止事项清单
代码层面
## ⚠️ 绝对禁止事项
### TypeScript相关
❌ **不要使用 `any` 类型**
```typescript
// ❌ 错误
function processData(data: any) { }
// ✅ 正确
function processData(data: unknown) { }
❌ 不要使用 as 强制类型断言(除非必要)
// ❌ 错误
const user = data as User;
// ✅ 正确
const user = isUser(data) ? data : null;
React相关
❌ 不要在JSX中使用匿名函数
// ❌ 错误(每次渲染都创建新函数)
<button onClick={() => handleClick(id)}>
// ✅ 正确
<button onClick={handleClick}>
❌ 不要直接修改state
// ❌ 错误
state.items.push(newItem);
setState(state);
// ✅ 正确
setState(prev => ({
...prev,
items: [...prev.items, newItem]
}));
安全相关
❌ 不要在代码中硬编码密钥
// ❌ 错误
const apiKey = 'sk_live_1234567890abcdef';
// ✅ 正确
const apiKey = process.env.API_KEY;
❌ 不要在生产环境输出错误堆栈
// ❌ 错误
res.send(err.stack);
// ✅ 正确
res.send('Internal Server Error');
性能相关
❌ 不要在渲染中执行昂贵计算
// ❌ 错误
function ExpensiveComponent() {
const result = heavyComputation(data); // 每次渲染都计算
return <div>{result}</div>;
}
// ✅ 正确
function ExpensiveComponent() {
const result = useMemo(() => heavyComputation(data), [data]);
return <div>{result}</div>;
}
Git相关
❌ 不要提交敏感文件
- .env文件
- 数据库备份(.sql, .db)
- 私钥文件(.pem, .key)
- 大文件(>50MB)
❌ 不要在主分支直接修改
- 所有改动通过分支PR
- 主分支受保护
❌ 不要推送未测试的代码
- 本地测试通过
- CI/CD检查通过
## 常见问题排查
### 问题诊断流程
```markdown
## 🔧 常见问题排查
### "Cannot find module" 错误
**原因**: 依赖未安装或路径错误
**解决方案**:
\`\`\`bash
# 1. 清理并重新安装依赖
rm -rf node_modules package-lock.json
npm install
# 2. 检查TypeScript路径别名配置
# tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["src/*"]
}
}
}
# 3. 重启TypeScript服务器(VSCode)
# Cmd+Shift+P -> "TypeScript: Restart TS Server"
\`\`\`
### 数据库连接失败
**症状**: `Connection refused` 或 `ECONNREFUSED`
**排查步骤**:
\`\`\`bash
# 1. 检查数据库服务是否运行
pg_isready # PostgreSQL
mysqladmin ping # MySQL
redis-cli ping # Redis
# 2. 检查环境变量
echo $DATABASE_URL
# 3. 测试连接
psql $DATABASE_URL
# 4. 查看数据库日志
tail -f /usr/local/var/postgres/log/server.log
\`\`\`
### TypeScript类型错误
**常见错误**: `Property 'xxx' does not exist on type 'yyy'`
**解决方案**:
\`\`\`typescript
// 1. 使用类型守卫
function isUser(data: unknown): data is User {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'name' in data
);
}
// 2. 使用类型断言(谨慎使用)
const user = data as User;
// 3. 定义更宽松的类型
interface UserProps {
[key: string]: unknown;
}
\`\`\`
### 测试超时
**症状**: Jest测试超时(默认5秒)
**解决方案**:
\`\`\`typescript
// 1. 增加超时时间
jest.setTimeout(10000);
test('async test', async () => {
// 测试代码
}, 10000);
// 2. 全局配置(jest.config.js)
module.exports = {
testTimeout: 10000
};
\`\`\`
### 端口被占用
**错误信息**: `Error: listen EADDRINUSE: address already in use :::3000`
**解决方案**:
\`\`\`bash
# 1. 查找占用端口的进程
lsof -i :3000
# 2. 杀死进程
kill -9 <PID>
# 3. 或使用其他端口
PORT=3001 npm run dev
\`\`\`
### CORS错误
**症状**:浏览器控制台显示跨域错误
**解决方案**:
\`\`\`typescript
// Express后端配置CORS
import cors from 'cors';
app.use(cors({
origin: ['http://localhost:3000', 'https://yourdomain.com'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
\`\`\`
多项目配置策略
Monorepo配置
对于使用Monorepo架构的项目,可以为每个子包创建独立的CLAUDE.md:
monorepo-root/
├── CLAUDE.md # 根级别配置(全局规范)
├── packages/
│ ├── frontend/
│ │ ├── CLAUDE.md # 前端特定配置
│ │ └── package.json
│ ├── backend/
│ │ ├── CLAUDE.md # 后端特定配置
│ │ └── package.json
│ └── shared/
│ ├── CLAUDE.md # 共享库配置
│ └── package.json
根级别CLAUDE.md:
# Monorepo全局配置
## 共享规范
- TypeScript配置: 统一使用tsconfig.base.json
- 代码风格: 统一ESLint和Prettier配置
- Git工作流: 统一提交规范和分支策略
- CI/CD: 统一构建和部署流程
## 依赖管理
- 使用workspace协议引用内部包
- 共享依赖提升到根目录
- 版本管理: 使用changesets
## 常用命令
\`\`\`bash
# 安装所有依赖
npm install
# 构建所有包
npm run build
# 测试所有包
npm run test
# 添加依赖(到特定包)
npm package-name -w packages/frontend
\`\`\`
## 子包特定配置
各子包的特定配置请参考:
- 前端: packages/frontend/CLAUDE.md
- 后端: packages/backend/CLAUDE.md
- 共享: packages/shared/CLAUDE.md
多语言项目
对于包含多种编程语言的项目:
# 多语言项目配置
## 项目结构
\`\`\`
project/
├── frontend/ # TypeScript/React
├── backend/ # Python/Django
├── ml-service/ # Python/PyTorch
└── mobile/ # Dart/Flutter
\`\`\`
## 全局规范
- API设计: RESTful,统一响应格式
- 数据格式: JSON
- 认证: JWT,统一token管理
- 日志: 结构化日志,统一格式
## 前端(TypeScript)
- 参见: frontend/CLAUDE.md
## 后端(Python)
- 参见: backend/CLAUDE.md
## 跨语言协作
### API定义(使用OpenAPI)
- API规范: api-spec/openapi.yaml
- 自动生成SDK: npm run generate:client
### 数据库变更
- 迁移管理: backend/database/migrations/
- 变更同步: 各服务负责人review
配置维护和演进
配置生命周期
## CLAUDE.md维护流程
### 创建阶段
1. 使用 `/init` 命令生成基础配置
2. 填充项目特定信息
3. 添加编码规范和最佳实践
4. 提交到版本控制
### 成长阶段
**每月审查**:
- [ ] 技术栈是否有变化?
- [ ] 是否有新的编码规范?
- [ ] 常用命令是否需要更新?
- [ ] 是否有新的常见问题?
**更新触发条件**:
✅ 引入新的框架或库
✅ 架构发生重大变更
✅ 团队规范更新
✅ 发现新的常见错误模式
✅ 项目规模扩大(需要更多规范)
### 成熟阶段
**季度审查**:
- 全面评估配置完整性
- 收集团队反馈
- 优化文档结构
- 移除过时内容
### 配置版本控制
\`\`\`bash
# 重大配置变更时创建分支
git checkout -b docs/update-claude-md
# 更新配置
vim CLAUDE.md
# 提交变更
git add CLAUDE.md
git commit -m "docs: update CLAUDE.md with new tech stack"
# 团队审查
git push origin docs/update-claude-md
# 创建Pull Request
\`\`\`
配置审查清单
## CLAUDE.md质量检查清单
### 完整性检查
- [ ] 项目概述清晰(目标、用户、价值)
- [ ] 技术栈完整(框架、工具、版本)
- [ ] 目录结构准确(与实际一致)
- [ ] 编码规范详细(命名、风格、示例)
- [ ] 常用命令有效(可以正常运行)
- [ ] 测试策略明确(覆盖率、工具)
- [ ] 部署流程清晰(步骤、注意事项)
### 准确性检查
- [ ] 所有示例代码可运行
- [ ] 版本号与package.json一致
- [ ] 路径和文件名真实存在
- [ ] 命令输出与实际相符
- [ ] 链接有效(文档、资源)
### 实用性检查
- [ ] 包含实际配置示例
- [ ] 禁止事项明确列出
- [ ] 常见问题有解决方案
- [ ] 代码示例有注释
- [ ] 结构清晰易查找
### 维护性检查
- [ ] 最后更新时间(<= 3个月)
- [ ] 过时内容已移除
- [ ] 新规范已补充
- [ ] 团队反馈已整合
团队协作最佳实践
配置同步策略
## 团队配置管理
### 配置层级
1. **企业级** - 全局规范(所有项目共享)
2. **团队级** - 团队规范(团队内所有项目)
3. **项目级** - 项目规范(./CLAUDE.md)
4. **个人级** - 个人偏好(~/.claude/CLAUDE.md)
### 配置继承
\`\`\`bash
# ~/.claude/CLAUDE.md (个人配置)
# 我偏好中文注释
# 我喜欢详细注释
# ./CLAUDE.md (项目配置)
# 项目使用TypeScript
# 项目使用函数式组件
# 企业级配置(如存在)
# 安全策略:禁止硬编码密钥
# 合规要求:数据必须加密
\`\`\`
### 配置优先级
企业级 > 团队级 > 项目级 > 个人级
### 配置更新流程
\`\`\`
┌─────────────┐
│ 提出变更 │
└──────┬──────┘
│
▼
┌─────────────┐
│ 团队讨论 │
└──────┬──────┘
│
▼
┌─────────────┐
│ 创建PR │
└──────┬──────┘
│
▼
┌─────────────┐
│ Code Review │
└──────┬──────┘
│
▼
┌─────────────┐
│ 合并更新 │
└──────┬──────┘
│
▼
┌─────────────┐
│ 通知团队 │
└─────────────┘
\`\`\`
### 配置冲突解决
当个人配置与项目配置冲突时:
1. **个人偏好**(如注释语言): 优先个人配置
2. **代码规范**(如命名风格): 优先项目配置
3. **安全策略**: 优先企业/团队配置
新成员onboarding
## 新成员快速上手指南
### 第1天: 环境搭建
\`\`\`bash
# 1. 克隆仓库
git clone <repo-url>
cd <project-name>
# 2. 安装依赖
npm install
# 3. 启动开发服务器
npm run dev
# 4. 阅读CLAUDE.md
cat CLAUDE.md
\`\`\`
### 第1周: 熟悉规范
**必读文档**:
- [ ] CLAUDE.md (项目配置)
- [ ] README.md (项目介绍)
- [ ] CONTRIBUTING.md (贡献指南)
- [ ] docs/architecture.md (架构文档)
**实践任务**:
- [ ] 创建一个简单的组件(遵循项目规范)
- [ ] 编写单元测试
- [ ] 提交PR(Claude Code审查)
### 第2周: 独立开发
- [ ] 完成一个小的feature
- [ ] 参与代码review
- [ ] 更新CLAUDE.md(如有需要)
### 新成员常见问题
**Q: 不确定某个规范?**
A: 查看CLAUDE.md或询问团队
**Q: 可以修改编码规范吗?**
A: 需要团队讨论和同意
**Q: CLAUDE.md不够详细?**
A: 提出issue或PR补充
实战案例
案例1: 重构项目配置
背景: 一个6个月的项目,配置文档已经过时
问题:
- 技术栈版本与实际不符
- 编码规范未包含新的团队约定
- 缺少新引入工具的说明
- 常见问题部分已过时
解决方案:
# 配置重构流程
## 第1步: 审查现有配置
\`\`\`bash
# 1. 对比实际配置
cat package.json | grep -E '"(react|typescript|eslint)":'
cat tsconfig.json
cat .eslintrc.js
# 2. 收集团队反馈
# 创建文档:"哪些配置需要补充?"
\`\`\`
## 第2步: 更新技术栈
\`\`\`markdown
## 技术栈(更新于: 2025-01-15)
### 实际版本(从package.json提取)
- React: 18.2.0
- TypeScript: 5.3.0
- Vite: 5.0.0 (从Webpack迁移)
### 新增工具
- Vitest: 替代Jest(更快的测试)
- Playwright: E2E测试
- Turbopack: 开发构建提速
\`\`\`
## 第3步: 补充编码规范
\`\`\`markdown
## 编码规范更新
### 新增: Hooks使用规范
\`\`\`typescript
// ✅ 正确: Hooks顺序
function MyComponent() {
// 1. useState
const [state, setState] = useState();
// 2. useContext
const context = useContext(MyContext);
// 3. 自定义Hooks
const custom = useCustom();
// 4. useEffect
useEffect(() => {}, []);
}
\`\`\`
### 新增: 错误边界规范
- 所有页面组件必须用ErrorBoundary包裹
- 错误必须上报到监控服务
\`\`\`
## 第4步: 添加实战示例
\`\`\`markdown
## 实战示例
### 创建新的API端点
完整流程:从定义到测试到文档
详见: docs/api-creation-workflow.md
\`\`\`
## 第5步: 更新常见问题
\`\`\`markdown
## 常见问题(更新)
### Q: Vitest测试报错 "Cannot find module"
A: 更新vite.config.ts,添加别名配置
\`\`\`typescript
export default defineConfig({
resolve: {
alias: {
'@': '/src'
}
}
});
\`\`\`
\`\`\`
## 第6步: 团队review和同步
\`\`\`bash
# 创建PR
git checkout -b docs/update-claude-md
git add CLAUDE.md
git commit -m "docs: update CLAUDE.md with current tech stack and new conventions"
git push origin docs/update-claude-md
# 团队review
# 合并后通知所有人
# 在团队会议上介绍变更
\`\`\`
案例2: 多项目统一配置
背景: 一个公司有10个类似项目,配置各不相同
目标: 统一配置,提高效率
实施:
# 多项目配置统一方案
## 方案1: 创建配置模板库
\`\`\`
company-templates/
├── node-react-typescript/
│ ├── CLAUDE.md.template
│ ├── .eslintrc.js
│ ├── tsconfig.json
│ └── .prettierrc
├── python-django/
│ └── ...
└── go-microservice/
└── ...
\`\`\`
## 方案2: 使用NPM包共享配置
\`\`\`json
// package.json
{
"devDependencies": {
"@company/eslint-config": "^1.0.0",
"@company/tsconfig": "^1.0.0",
"@company/prettier-config": "^1.0.0"
}
}
\`\`\`
\`\`\`javascript
// .eslintrc.js
module.exports = {
extends: ['@company/eslint-config'],
rules: {
// 项目特定规则
}
};
\`\`\`
## 方案3: Monorepo + 共享配置
\`\`\`
monorepo/
├── packages/
│ ├── config/
│ │ ├── claude-md-base.md
│ │ ├── eslint-config/
│ │ └── tsconfig/
│ ├── project-a/
│ └── project-b/
\`\`\`
## 实施效果
- 新项目启动时间: 2小时 -> 30分钟
- 配置一致性: 60% -> 95%
- 新成员上手时间: 3天 -> 1天
配置自动化工具
自动生成CLAUDE.md
#!/bin/bash
# scripts/generate-claude-md.sh
echo "生成CLAUDE.md配置文件..."
# 1. 提取项目信息
PROJECT_NAME=$(cat package.json | jq -r '.name')
PROJECT_VERSION=$(cat package.json | jq -r '.version')
# 2. 提取主要依赖
MAIN_DEPS=$(cat package.json | jq -r '.dependencies | keys | join(", ")')
# 3. 提取脚本命令
SCRIPTS=$(cat package.json | jq -r '.scripts | to_entries | map(" - \(.key): \(.value)") | join("\n")')
# 4. 生成配置文件
cat > CLAUDE.md << EOF
# $PROJECT_NAME
## 项目概述
自动生成的配置文件
## 技术栈
主要依赖: $MAIN_DEPS
## 常用命令
$SCRIPTS
## 配置生成时间
$(date '+%Y-%m-%d %H:%M:%S')
## 注意事项
请手动完善以下内容:
- 项目架构说明
- 编码规范
- 测试策略
- 部署流程
EOF
echo "✅ CLAUDE.md已生成"
echo "⚠️ 请手动完善配置内容"
配置验证工具
// scripts/validate-claude-md.js
const fs = require('fs');
const path = require('path');
function validateCLAUDEmd(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
const errors = [];
const warnings = [];
// 检查必需的章节
const requiredSections = [
'项目概述',
'技术栈',
'目录结构',
'编码规范',
'常用命令'
];
requiredSections.forEach(section => {
if (!content.includes(section)) {
errors.push(`缺少必需章节: ${section}`);
}
});
// 检查版本号是否与package.json一致
const pkg = require('../package.json');
if (content.includes('version:') && !content.includes(pkg.version)) {
warnings.push('CLAUDE.md中的版本号可能与package.json不一致');
}
// 检查是否有示例代码
if (!content.includes('```')) {
warnings.push('建议添加代码示例');
}
// 检查是否有常见问题部分
if (!content.toLowerCase().includes('常见问题') &&
!content.toLowerCase().includes('troubleshooting')) {
warnings.push('建议添加常见问题部分');
}
return { errors, warnings };
}
// 运行验证
const result = validateCLAUDEmd('./CLAUDE.md');
console.log('CLAUDE.md验证结果:');
if (result.errors.length > 0) {
console.log('\n❌ 错误:');
result.errors.forEach(err => console.log(` - ${err}`));
process.exit(1);
}
if (result.warnings.length > 0) {
console.log('\n⚠️ 警告:');
result.warnings.forEach(warn => console.log(` - ${warn}`));
}
console.log('\n✅ 配置文件验证通过!');
总结
配置最佳实践核心要点
-
从简入手,逐步完善
- 用
/init快速生成基础配置 - 根据需要补充
- 别过度配置
- 用
-
保持准确和更新
- 定期审查(每月/季度)
- 重大变更及时更新
- 删掉过时内容
-
用代码示例
- 示例比文字清楚
- 确保示例能跑
- 加注释说明
-
明确禁止事项
- 列出常见错误
- 说明为什么不这样
- 给出正确做法
-
团队协作
- 配置纳入版本控制
- 变更需要团队review
- 定期同步更新
-
分层管理
- 个人偏好和项目规范分开
- 企业级和项目级配置独立
- 理解优先级
配置带来的价值
完善的CLAUDE.md配置可以:
- ✅ 效率提升70%: 减少重复沟通和返工
- ✅ 首次正确率95%: 代码一次生成符合规范
- ✅ 错误减少85%: 避免常见错误和陷阱
- ✅ 新成员上手快50%: 快速了解项目规范
- ✅ 统一团队标准: 所有人遵循同一规范
下一步
立即行动:
- 创建或更新项目的CLAUDE.md
- 用本指南的模板作为起点
- 根据实际情况定制
- 提交到版本控制并分享给团队
持续改进:
- 设置日历提醒(每月审查配置)
- 收集团队反馈
- 记录新的常见问题和解决方案
- 保持与项目同步演进
参考资源
官方文档
相关工具
社区资源
作者: Claude Code团队 更新时间: 2025-01-15 版本: 1.0.0
相关文章: