实战:路径与工作流

Claude Code 最佳实践与工作流

更新 原创整合
标签
claude-codebest-practicesworkflow

核心原则:上下文是最重要的资源

Claude Code 的所有最佳实践都围绕一个约束:上下文窗口会快速填满,越满性能越差。上下文包含对话历史 + 读取的文件 + 命令输出。

→ 管理上下文 = 管理 Claude Code 的性能。


原则一:给 Claude 验证方式

这是效果提升最大的单一操作。

场景 低效 高效
实现功能 "implement validateEmail" "write validateEmail, test: user@example.com→true, invalid→false, run tests after"
UI 修改 "make it look better" "[截图] implement this design, take screenshot and compare"
修错误 "build is failing" "build fails: [完整错误栈], fix and verify build succeeds"

原则二:探索 → 规划 → 编码

# 阶段 1:Plan Mode(只读不写)
claude --permission-mode plan
> read /src/auth and understand how we handle sessions

# 阶段 2:规划
> What files need to change to add Google OAuth? Create a plan.
# Ctrl+G 在编辑器中编辑计划

# 阶段 3:实现(Shift+Tab 切回 Normal Mode)
> implement the OAuth flow from your plan

# 阶段 4:提交
> commit with a descriptive message

小任务(改变量名、加日志)可以跳过规划。


原则三:提供精确上下文

技巧 示例
@ 引用文件 look at @src/auth/login.ts
粘贴截图 直接拖进来
给 URL 让 Claude 读文档链接
管道输入 cat error.log | claude

常见工作流

探索新代码库

give me an overview of this codebase
explain the main architecture patterns
find the files that handle user authentication
trace the login process from front-end to database

修 Bug

# 给完整错误信息
I'm seeing an error when I run npm test
[paste full error stack]
fix it and verify the build succeeds

代码重构

find deprecated API usage in our codebase
refactor utils.js to use ES2024 features, maintain same behavior
run tests for the refactored code

写测试

find functions in NotificationsService.swift not covered by tests
add tests for the notification service
run the new tests and fix any failures

创建 PR

create a pr for my changes
# 或分步
summarize the changes I've made
create a pr

并行开发(Worktree)

claude --worktree feature-auth    # 终端 1
claude --worktree bugfix-login    # 终端 2
# 不同 worktree 互不干扰,完成后自动清理

Unix 管道

cat build-error.txt | claude -p 'concisely explain the root cause'
cat code.py | claude -p 'analyze for bugs' --output-format json

上下文管理

操作 命令 用途
清除 /clear 不相关任务之间分隔
压缩 /compact Focus on API changes 保留关键信息,丢弃无关对话
子 Agent Use subagents to investigate X 探索在子 Agent 完成,不污染主上下文
回退 Esc+Esc 撤回并恢复之前的代码状态
命名 claude -n auth-refactor 给会话命名,后续 claude --resume 恢复

多 Agent 协作

子 Agent(临时探索)

Use subagents to investigate how auth handles token refresh

子 Agent 独立启动,搜索文件,只把摘要返回主会话,不污染主上下文。

自定义 Agent(持久专用)

.claude/agents/ 创建 markdown 文件:

<!-- .claude/agents/reviewer.md -->
---
name: reviewer
description: Code review specialist
tools: Read, Grep, Glob
model: claude-sonnet-4-6
---
You are a code review specialist. Check security, performance,
error handling, and code style. Rate: Critical/Warning/Suggestion.

调用:@reviewer Check the latest commit for security issues

Agent 团队(并行协作)

I need to refactor the auth module.
Use agent teams to:
- Agent 1: Refactor login flow
- Agent 2: Refactor token management
- Agent 3: Refactor session handling
Each agent works on a separate worktree.
层级 名称 适合
子 Agent 临时探索 快速调查,不污染上下文
自定义 Agent 持久专用 代码审查、测试生成等反复执行的任务
Agent 团队 并行协作 大型重构、多人协作

CI/CD 集成(无头模式)

基本用法

# 非交互执行
claude -p "fix all lint errors" --allowedTools "Edit,Bash(npm run lint)"

# JSON 输出
claude -p "List all API endpoints" --output-format json

# 限制轮数
claude -p "fix the bug" --max-turns 10 --permission-mode auto

GitHub Actions

PR 中 @claude 即触发:

# .github/workflows/claude-review.yml
name: Claude Code Review
on:
  issue_comment:
    types: [created]

jobs:
  review:
    if: contains(github.event.comment.body, '@claude')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
触发 命令 Claude 行为
PR 评论 @claude review this PR 审查代码变更
Issue 评论 @claude fix this issue 分析并提交修复
定时 schedule: cron 每日代码质量检查

SDK 编程调用

import { query } from "@anthropic-ai/claude-code";

const result = await query({
  prompt: "Explain the auth flow",
  options: {
    maxTurns: 5,
    allowedTools: ["Read", "Grep", "Glob"],
  },
});

安全建议

# 最小权限
claude -p "refactor" --allowedTools "Edit,Read,Grep,Glob" --permission-mode auto

# 限制 Bash 范围
claude -p "run tests" --allowedTools "Bash(npm test)"

# 限制轮数防止失控
claude -p "fix" --max-turns 10

社区精选技巧

来自 Claude Code 创建者 Boris Cherny 和社区的验证技巧:

"先面试我"技巧

I want to build [brief description].
Interview me in detail using AskUserQuestion.
Ask about technical implementation, UI/UX, edge cases.
Keep interviewing until we've covered everything, then write SPEC.md.

三阶段效率系统

StarMorph 团队:Opus 做深度研究 → 详细计划 → Sonnet 快速实现。7 小时完成 1-2 周工作量。

生产环境经验

TypeScript 微服务团队(6 个月)总结:用 Hook 激活技能、分层 CLAUDE.md、CI/CD 集成 PR 自动审查。

"Genome" 文件方法

维护架构原则文件,跨会话保持一致性。核心教训:跳过规划阶段是致命的


常见陷阱

陷阱 症状 解决
堆砌会话 上下文杂乱 /clear 分隔任务
反复纠错 改了 3 次还不对 清空上下文,重写 prompt
CLAUDE.md 过长 Claude 忽略部分指令 精简到 200 行以内
无限探索 读了几百个文件 明确范围,用子 Agent
跳过验证 边界情况没处理 永远提供验证方式
过度定制 配太多 Hook 变慢 只配置真正常用的