AI 驱动开发最佳实践
Claude Code 开启了一个全新的开发時代。这些最佳实践经过实际项目验证,帮助开发者充分利用 AI 的能力,同时保持代码质量和可维护性。
核心开发原则
1. CLAUDE.md 优先原则
始终从 CLAUDE.md 开始任何项目
# 最小化可行的 CLAUDE.md 结构
## 项目概述
一句话描述项目目标和价值。
## 技术栈
- 前端: React 18 + TypeScript
- 后端: Node.js + Express
- 数据库: PostgreSQL
- 部署: Docker + AWS
## 代码风格
- ESLint + Prettier
- 函数式编程优先
- TypeScript strict 模式
## 当前任务
- [ ] 实现用户认证系统
- [ ] 添加数据验证层
为什么重要:
- 给 AI 提供必要的上下文
- 确保代码风格一致性
- 跟踪项目进度和目标
- 方便团队协作
2. 上下文驱动开发
建立深度上下文:
# 项目初始化时
claude "分析现有代码库结构,创建 CLAUDE.md"
# 新功能开发时
claude "基于现有架构,设计用户管理模块"
# 问题修复时
claude "分析相关组件和依赖,修复这个错误"
上下文分层管理:
全局上下文 (CLAUDE.md)
│
├── 项 目级配置和约定
│
├── 模块级上下文 (components/CLAUDE.md)
│ ├── 组件设计原则
│ └── API 设计规范
│
└── 任务级上下文 (代码注释和文档)
└── 特定实现细节
3. AI 辅助的渐进式开发
小步快跑原则:
# 每个功能都从 MVP 开始
claude "实现用户登录的最简版本,只包括基本功能"
# 逐步增强
claude "为登录功能添加错误处理和用户反馈"
# 最后优化
claude "优化登录流程的性能和用户体验"
迭代周期管理:
- 快速原型 (1-2天) → 验证核心概念
- 功能完善 (3-5天) → 添加必要特性
- 质量优化 (2-3天) → 性能、安全、可用性
- 文档完善 (1天) → 更新相关文档
代码质量保障
TypeScript 最佳实践
严格类型配置:
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitReturns": true,
"noImplicitOverride": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}
智能类型推导:
// 好的做法:让 AI 生成类型安全的代码
type User = {
id: string;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
createdAt: Date;
};
type CreateUserRequest = Omit<User, 'id' | 'createdAt'>;
const createUser = async (data: CreateUserRequest): Promise<User> => {
// AI 生成的验证逻辑
if (!data.email.includes('@')) {
throw new Error('Invalid email format');
}
// 类型安全的数据创建
return {
id: crypto.randomUUID(),
...data,
createdAt: new Date()
};
};
// 避免:任意使用 any
const badFunction = (data: any) => {
// 无法利用 TypeScript 的类型检查
return data.whatever.something;
};
函数式编程最佳实践
纯函数优先:
// 好:纯函数,易于测试和理解
const calculateOrderTotal = (
items: CartItem[],
taxRate: number,
discountCode?: string
): OrderTotal => {
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const discount = discountCode ? calculateDiscount(subtotal, discountCode) : 0;
const tax = (subtotal - discount) * taxRate;
return {
subtotal,
discount,
tax,
total: subtotal - discount + tax
};
};
// 避免:可变状态和副作用
let globalOrderState = {}; // 避免全局状态
const badCalculateTotal = (items) => {
globalOrderState.total = 0; // 副作用
// 复杂的可变操作...
};
组合优于继承:
// 好:使用组合和高阶函数
const withLogging = <T extends (...args: any[]) => any>(fn: T): T => {
return ((...args) => {
console.log(`Calling ${fn.name} with`, args);
const result = fn(...args);
console.log(`Result:`, result);
return result;
}) as T;
};
const withRetry = <T extends (...args: any[]) => Promise<any>>(
fn: T,
maxRetries: number = 3
): T => {
return (async (...args) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn(...args);
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}) as T;
};
// 使用组合
const apiCall = withRetry(withLogging(fetchUserData));
React 最佳实践
组件设计原则:
// 好:单一职责原则
interface UserProfileProps {
userId: string;
onUpdate?: (user: User) => void;
}
const UserProfile: React.FC<UserProfileProps> = ({ userId, onUpdate }) => {
const { user, loading, error } = useUser(userId);
if (loading) return <LoadingSpinner />;
if (error) return <ErrorMessage error={error} />;
if (!user) return <NotFound />;
return (
<div className="user-profile">
<UserAvatar user={user} />
<UserInfo user={user} />
<UserActions user={user} onUpdate={onUpdate} />
</div>
);
};
// 避免:巨大的多功能组件
const BadUserComponent = () => {
// 500+ 行的 组件代码
// 处理数据获取、表单验证、UI 渲染、状态管理...
};
性能优化最佳实践:
// React.memo + useMemo + useCallback 组合
const UserList = React.memo<{ users: User[]; onUserSelect: (id: string) => void }>(({
users,
onUserSelect
}) => {
// 缓存排序结果
const sortedUsers = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
);
// 稳定的回调函数引用
const handleSelect = useCallback(
(id: string) => onUserSelect(id),
[onUserSelect]
);
return (
<div>
{sortedUsers.map(user => (
<UserItem
key={user.id}
user={user}
onSelect={handleSelect}
/>
))}
</div>
);
});
// 虚拟化长列表
const VirtualUserList = ({ users }: { users: User[] }) => {
const parentRef = useRef<HTMLDivElement>(null);
const { virtualItems, totalSize } = useVirtual({
size: users.length,
parentRef,
estimateSize: useCallback(() => 60, []),
overscan: 5
});
return (
<div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
<div style={{ height: totalSize, width: '100%', position: 'relative' }}>
{virtualItems.map(virtualRow => (
<div
key={virtualRow.index}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: virtualRow.size,
transform: `translateY(${virtualRow.start}px)`
}}
>
<UserItem user={users[virtualRow.index]} />
</div>
))}
</div>
</div>
);
};
AI 辅助开发最佳实践
有效的 AI 交互
提供充分上下文:
# 好:具体的上下文
claude "在这个 React + TypeScript 项目中,实现一个用户表单,需要支持实时验证和异步提交。使用 React Hook Form + Zod。"
# 避免:模糊的请求
claude "写个表单" # 太简单
claude "做一个网站" # 范围太大
阶段性开发请求:
# 第一阶段:基本实现
claude "创建基本的用户表单结构,只包括姓名、邮箱、密码字段"
# 第二阶段:增强功能
claude "为表单添加实时验证,邮箱格式检查和密码强度验证"
# 第三阶段:体验优化
claude "优化表单的加载状态和错误处理,添加成功反馈"
代码生成策略
分层生成原则:
- 数据层 → 类型定义和数据验证
- 逻辑层 → 业务逻辑和 API 调用
- 组件层 → UI 组件和交互逻辑
- 集成层 → 页面组合和路由
# 第一步:数据模型
claude "为用户管理系统设计 TypeScript 类型和 Zod 验证模式"
# 第二步: API 层
claude "基于类型定义,实现用户 CRUD API 函数"
# 第三步:组件层
claude "创建用户表单组件,使用之前的 API 函数"
# 第四步:页面集成
claude "将所有组件集成到用户管理页面"
代码审查和优化
自动化审查流程:
# 代码完成后的检查清单
claude "审查这个组件:1.性能 2.安全性 3.可访问性 4.错误处理 5.代码质量"
# 重构建议
claude "分析这个模块的复杂度,提出重构建议"
# 测试覆盖率
claude "为这个函数生成单元测试,確保 100% 覆盖率"
项目结构最佳实践
文件组织策略
src/
│
├── types/ # 全局类型定义
│ ├── api.ts
│ ├── user.ts
│ └── common.ts
│
├── utils/ # 公用工具函数
│ ├── validation.ts
│ ├── formatting.ts
│ └── api-client.ts
│
├── hooks/ # 自定义 React Hooks
│ ├── useUser.ts
│ ├── useApi.ts
│ └── useLocalStorage.ts
│
├── components/ # 可复用组件
│ ├── ui/ # 基础 UI 组件
│ │ ├── Button/
│ │ ├── Input/
│ │ └── Modal/
│ └── features/ # 功能组件
│ ├── UserForm/
│ └── UserList/
│
├── pages/ # 页面组件
│ ├── Dashboard/
│ ├── Users/
│ └── Settings/
│
└── services/ # API 和外部服务
├── userService.ts
└── authService.ts
命名约定:
// 文件命名:kebab-case
user-profile.component.tsx
api-client.utils.ts
user-management.page.tsx
// 组件命名:PascalCase
export const UserProfile = () => { ... };
export const ApiClient = { ... };
// 函数和变量:camelCase
const fetchUserData = async () => { ... };
const isLoading = false;
// 常量:SCREAM_CASE
const API_BASE_URL = 'https://api.example.com';
const MAX_RETRY_ATTEMPTS = 3;
// 类型和接口:PascalCase
interface UserProfile { ... }
type ApiResponse<T> = { ... };
配置管理
// config/index.ts - 分层配置
interface Config {
api: {
baseUrl: string;
timeout: number;
retryAttempts: number;
};
features: {
enableAnalytics: boolean;
enableDarkMode: boolean;
enableBetaFeatures: boolean;
};
ui: {
pageSize: number;
theme: 'light' | 'dark' | 'auto';
};
}
const config: Config = {
api: {
baseUrl: process.env.REACT_APP_API_URL || 'http://localhost:3001',
timeout: Number(process.env.REACT_APP_API_TIMEOUT) || 10000,
retryAttempts: Number(process.env.REACT_APP_RETRY_ATTEMPTS) || 3
},
features: {
enableAnalytics: process.env.NODE_ENV === 'production',
enableDarkMode: true,
enableBetaFeatures: process.env.REACT_APP_ENABLE_BETA === 'true'
},
ui: {
pageSize: 20,
theme: 'auto'
}
};
export default config;