跳至主要内容

專案配置最佳實踐

配置做得好,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>
);
}
__CODE_BLOCK_6__json
{
"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"
}
}
__CODE_BLOCK_7__typescript
/**
* 用户服务类
* 负责用户相关的业务逻辑和数据操作
*/
export class UserService {
/**
* 根据用户ID获取用户信息
* @param userId - 用户ID,必须是有效的UUID格式
* @returns 返回用户对象,如果用户不存在则返回null
* @throws {InvalidUserIdError} 当userId格式无效时抛出
* @example
* __CODE_BLOCK_8__
*/
async getById(userId: string): Promise<User | null> {
// 实现逻辑
}
}
__CODE_BLOCK_9__bash
# 安装依赖
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类型检查
__CODE_BLOCK_10__bash
# 运行所有测试
npm test

# 运行测试并生成覆盖率报告
npm run test:coverage

# 监听模式(开发时使用)
npm run test:watch

# 运行E2E测试
npm run test:e2e
__CODE_BLOCK_11__bash
# 数据库迁移
npm run db:migrate # 执行迁移
npm run db:rollback # 回滚迁移
npm run db:seed # 填充种子数据

# 数据库客户端
npm run db:studio # 打开数据库管理界面
__CODE_BLOCK_12__bash
# 提交前检查
npm run prepare # Husky钩子,自动运行lint和test

# 代码提交(使用Commitlint)
git commit # 交互式提交,遵循约定式提交规范
__CODE_BLOCK_13__
main # 生产分支,受保护
├── develop # 开发分支
├── feature/* # 功能分支
├── bugfix/* # 修复分支
└── hotfix/* # 紧急修复分支
__CODE_BLOCK_14__
<type>(<scope>): <subject>

<body>

<footer>
__CODE_BLOCK_15__
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
__CODE_BLOCK_16__bash
# .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
__CODE_BLOCK_17__typescript
// 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');
}
__CODE_BLOCK_18__
env/
├── .env.example # 模板(提交)
├── .env.development # 开发环境(本地,不提交)
├── .env.staging # 预发布环境(部署时注入)
└── .env.production # 生产环境(部署时注入)
__CODE_BLOCK_19__gitignore
# .gitignore
.env
.env.local
.env.*.local
*.env
__CODE_BLOCK_20__
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 # 删除
__CODE_BLOCK_21__json
{
"success": true,
"data": {
"id": "123",
"name": "Resource Name"
},
"message": "操作成功",
"meta": {
"timestamp": "2025-01-15T10:30:00Z",
"version": "1.0.0"
}
}
__CODE_BLOCK_22__json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "请求参数验证失败",
"details": [
{
"field": "email",
"message": "邮箱格式不正确"
}
]
},
"meta": {
"timestamp": "2025-01-15T10:30:00Z",
"requestId": "req_abc123"
}
}
__CODE_BLOCK_23__typescript
// 通过URL路径版本化
// api/v1/users
// api/v2/users

// 或通过Header版本化
// Accept: application/vnd.api+json; version=1
__CODE_BLOCK_24__
/\
/ \ E2E测试 (10%)
/____\ - 关键用户流程
/ \ - 使用Playwright/Cypress
/ \ - 集成测试 (30%)
/ \ - API测试
/____________\ - 组件集成
/ \ - 单元测试 (60% - 优先)
/ \ - 函数/类/组件单元测试
__CODE_BLOCK_25__typescript
// 单元测试示例
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();
});
});
});
__CODE_BLOCK_26__typescript
// 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: '令牌无效或已过期' }
});
}
}
__CODE_BLOCK_27__typescript
__IMPORT_158__

// 请求验证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
}
});
}
}
}
__CODE_BLOCK_28__typescript
// 1. 代码分割
__IMPORT_159__

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✅ 配置文件验证通过!');

總結

配置最佳實踐核心要點

  1. 從簡入手,逐步完善

    • /init 快速生成基礎配置
    • 根據需要補充
    • 別過度配置
  2. 保持準確和更新

    • 定期審查(每月/季度)
    • 重大變更及時更新
    • 刪掉過時內容
  3. 用程式碼示例

    • 示例比文字清楚
    • 確保示例能跑
    • 加註釋說明
  4. 明確禁止事項

    • 列出常見錯誤
    • 說明為什麼不這樣
    • 給出正確做法
  5. 團隊協作

    • 配置納入版本控制
    • 變更需要團隊review
    • 定期同步更新
  6. 分層管理

    • 個人偏好和專案規範分開
    • 企業級和專案級配置獨立
    • 理解優先順序

配置帶來的價值

完善的CLAUDE.md配置可以:

  • 效率提升70%: 減少重複溝通和返工
  • 首次正確率95%: 程式碼一次生成符合規範
  • 錯誤減少85%: 避免常見錯誤和陷阱
  • 新成員上手快50%: 快速瞭解專案規範
  • 統一團隊標準: 所有人遵循同一規範

下一步

立即行動:

  1. 建立或更新專案的CLAUDE.md
  2. 用本指南的模板作為起點
  3. 根據實際情況定製
  4. 提交到版本控制並分享給團隊

持續改進:

  1. 設定日曆提醒(每月審查配置)
  2. 收集團隊反饋
  3. 記錄新的常見問題和解決方案
  4. 保持與專案同步演進

參考資源

官方文件

相關工具

社羣資源


作者: Claude Code團隊 更新時間: 2025-01-15 版本: 1.0.0

相關文章: