完整指南:CLAUDE.md — 将 Claude Code 转化为你的项目定制 AI

发布: (2026年3月13日 GMT+8 23:26)
5 分钟阅读
原文: Dev.to

Source: Dev.to

If Claude Code’s output feels generic, the fix is simple: write a CLAUDE.md file.
CLAUDE.md is a configuration file you place at your project root. Claude Code reads it automatically on every interaction, following your project‑specific rules instead of guessing.

为什么 CLAUDE.md 很重要

没有 CLAUDE.md,Claude Code 会对以下内容做出假设:

  • 你的编码约定(制表符还是空格、命名风格)
  • 你的架构(新文件放在哪里)
  • 你的测试策略(测试什么、如何测试)
  • 你的构建命令(如何运行、lint、部署)

有了 CLAUDE.md,你可以明确地定义所有这些。差异非常显著:

指标之前之后
首次可用输出40 %85 %
代码审查问题5‑8 每个 PR1‑2 每个 PR
测试覆盖率~30 %80 %+

四段结构

每个有效的 CLAUDE.md 包含以下章节:

# CLAUDE.md

快速参考

[团队每天运行的命令]

架构

[目录结构和设计模式]

规则

[编码约定,测试要求]

约束条件

[不该做的事]


## 模板 1:Python 后端(FastAPI)

```markdown
# CLAUDE.md

快速参考

运行: make dev | 测试: make test | Lint: make lint
DB: make db-migrate | Docker: docker compose up -d

Architecture

  • app/routers/ — 轻量 API 端点
  • app/services/ — 业务逻辑
  • app/models/ — SQLAlchemy ORM
  • app/core/ — 配置、认证、中间件

Rules

  • Routers parse requests → call services → return responses (no business logic)
  • New endpoints MUST have auth tests: 401, 403, 404, 422
  • Secrets via os.environ.get("KEY", "") — never hardcode defaults
  • Max 300 lines per router, 400 per service file

模板 2:React/Next.js 前端

# CLAUDE.md

快速参考

开发: npm run dev | 构建: npm run build | 测试: npm test

架构

  • src/components/ — 可复用的 UI 组件
  • src/features/ — 功能模块
  • src/hooks/ — 自定义 Hook
  • src/lib/ — 实用工具、API 客户端
## Rules
- Function components + TypeScript only  
- State: React Query (server), `useState`/`useReducer` (local)  
- Styling: Tailwind CSS only — no inline styles  
- Import order: React → libraries → internal → types  
- Accessibility: `aria-label` on buttons, `alt` on images

模板 3:数据科学 / 机器学习

# CLAUDE.md

快速参考

Jupyter: jupyter lab | 测试: pytest tests/

架构

  • notebooks/ — 探索(编号:01_02_
  • src/data/ — 数据获取,预处理
  • src/models/ — 模型定义,训练
  • src/evaluation/ — 指标,可视化

规则

  • 仅将笔记本用于探索——生产代码放在 src/
  • 数据路径来自 config.yaml(绝不硬编码)
  • 随机种子 必须 固定(可复现性)
  • 大型数据文件列入 .gitignore

3 需要避免的反模式

1. 模糊规则

# ❌ Bad
- Write clean code
- Write tests

# ✅ Good
- Functions max 50 lines. Split if longer
- Every new API endpoint needs auth tests (401/403)

具体的数字和条件可以让 AI 精确遵循规则。

2. 太长

一个 1,000 行的 CLAUDE.md 弊大于利——会占用上下文窗口。保持在 50‑150 行。对于更大的项目,拆分到 .claude/rules/ 中:

.claude/
  rules/
    development.md
    architecture.md
    testing.md

Claude Code 会自动加载 .claude/rules/ 中的文件。

3. 缺少命令

如果没有 Quick Reference(快速参考)章节,AI 会自行猜测要运行的命令。请始终包含:

快速参考

Dev: npm run dev | Test: npm test | Lint: npm run lint

立即开始

复制上面的任意模板,为你的项目进行定制,并将其保存为项目根目录下的 CLAUDE.md。整个过程大约需要 15 分钟,并且会从根本上改变 Claude Code 与你的代码库的交互方式。

想要使用 AI 搭建专业的开发环境吗?DigitalOcean 提供 $200 的免费额度——非常适合运行你的开发服务器、CI/CD 流水线和预演环境。

使用 Claude Code 开发中?在评论中分享你的 CLAUDE.md 配置吧——我很想看看大家是如何设置项目的。

0 浏览
Back to Blog

相关文章

阅读更多 »