跳转至

如何优雅地使用claude-code

近期入坑claude-code, 本文分享一下笔者常用的“省token小妙招”与“在claude辅助下开发项目”的心得 🌟

最近在小🍠上刷见一位大神的claude-code使用心得, 顿悟!

原文: How I Use Every Claude Code Feature

同时, 最近发现claude code的官方文档和开发者平台教程也更新了不少内容, 很有学习意义, 这里放个链接:


有一些非常不错的功能, 笔者强烈推荐大家去尝试一下, 这一小块内容会持续更新: (latest update: 2026-01-10)

  • 常见CC工作流程: 熟悉日常工作流, 和常见默认指令
  • CC在Github Actions中使用: 将 CC 集成到 CI/CD 流水线, 大幅降低对 issues/PRs 的压力
  • 子代理: 定义专门的子代理, 让claude在不同场景下使用不同模型/提示词. "构建不同的claude人格"
  • 安装好用的插件提高效率
    • commit-commands: Git 提交工作流,包括提交、推送和 PR 创建 (再也不用手写一堆 commit / PR description 了)
    • pr-review-toolkit: 用于审查拉取请求的专门代理 (自动审PR, 生成变更日志, 代码质量检查)
    • agent-sdk-dev: 使用 Claude Agent SDK 构建的工具
    • plugin-dev: 用于创建您自己的插件的工具包
  • skills: 定制claude处理流水线, 根据对话内容自动触发
  • CC Hooks: 在claude对话中自动触发外部脚本/命令行工具, 实现"人机协作" (常用于 pre-commit 检查, 代码格式化, 运行测试)
  • CC MCP: 连接外部工具
    • 笔者常用: 连接 github, CLI远程操控 (网页能做的, CLI都能做)
  • CC code-simplifier agent: 自动代码检查和重构
    • 2026-01-09 新增功能
    • 安装: claude plugin install code-simplifier
    • 功能: 在绝对不改变代码功能的前提下, 帮你把代码变得更简洁优雅 (linting + refactoring)

受上述启发, 笔者也准备写一个自用帖.

笔者采用的是 "Claude Code(CLI) + Pro 订阅(5小时限额)" 的方式. 有限额, 虽然平常开发已全部够用, 但还是想着有没有一些小tricks可以“能省则省”.

本文分享一下笔者常用的“省token小妙招”与“在claude辅助下开发项目”的心得.

核心逻辑:

  1. 减少不必要的 Context(上下文)输入, 把 token 用在刀刃上
  2. 让claude最大程度理解我的问题、理清代码框架、正确满足我的需求

优雅聪明地初始化

  • /init: 项目的“入职培训”
  • CLAUDE.md: 项目的“员工手册”

(1) /init:

当你第一次在一个新项目目录里打开 claude 时, 应该做的第一件事就是输入 /init

它会快速扫描你的整个文件夹, 尝试理解:

  • 这是一个什么项目? (Python? Node.js? Go?)
  • 用什么构建工具? (Make? Webpack? Gradle?)
  • 怎么运行测试? (pytest? npm test?)
  • 怎么启动服务?

产物: 扫描完成后, 会生成一个文件, 就叫 CLAUDE.md

(2) 在 CLAUDE.md 中明确任务需求/执行方法:

这是 /init 生成的文件,也是最重要的配置文件. 它通常位于项目根目录.

你可以把它理解为专门写给 AI 看的 README ("Claude 的宪法")

  • Commands
  • Code Style
  • Code Structure (Project Architecture)
  • 个人偏好:
    • "注释全部用英文"
    • "用uv构建这个python项目"
    • "python 版本3.10"
    • 省钱: "Be concise. Do not explain code unless asked."
    • 省钱: "When fixing bugs, only output the modified function, not the whole file."

检查上下文空间

Motivation:

为什么"会话的上下文"这么重要:

(1) 记忆性:

Claude 的上下文窗口虽然很大(e.g. 200k), 但并非无限

  • 截断风险: 当对话历史(Messages)过长时, Claude 会自动丢弃最早的对话记录
    • 如果开发者正在进行跨文件的复杂重构, 一旦关键的架构设计或之前的修改指令被“挤出”上下文, Claude 就会开始犯错或产生幻觉
  • 提前预判: 通过 /context 查看 Free space 和 Autocompact buffer, 开发者可以决定是否需要在关键逻辑开始前手动执行 /compact 或重启会话(/clear)
    • 对比一下/compact前后的上下文使用情况:

(2) 确保"推理质量":

上面提到"记忆与幻觉", 一个很直观的体验是:

模型在处理 30% 占用的任务时, 通常比处理 90% 占用的任务更精准

  • 注意力稀释: 上下文越拥挤, 背景噪音(不相关的代码片段、旧的报错日志) 就越多
  • 精简提效: 开发者会根据 /context 的反馈, 清理掉不再需要的 Skills 或 Custom agents, 确保 Claude 的 "注意力"全神贯注 在当前的代码逻辑上

Implementation:

Bash
1
2
3
claude
# 在终端会话中输入以下指令:
/context

运行后, Claude 会显示详细的上下文统计信息, 包括:

  • Total context window: 总上下文窗口大小 (如 200,000 tokens)
  • Current usage: 当前已使用的 token 数量及百分比
  • Breakdown: 消耗的分布情况(例如:Messages 消息记录、Files 文件内容、Tools 工具调用等占用的 token)

比如以我的当前会话效果为例, 输出是:

alt text

(1) Context Usage:

  • System prompt (1.5%): Claude 的“出厂设置”, 包含它的身份定义、核心指令和行为准则
  • System tools (8.8%): Claude 自带的基础工具(如读写文件、运行终端命令、搜索文件等)的定义
    • 这部分占用较大(17.6k)是因为工具定义的描述非常详细, 以确保模型能准确调用
  • MCP tools (2.6%): 用户通过 MCP 扩展的外部工具
    • 从下方详情看, 笔者主要连接了 GitHub 相关的服务
  • Messages (19.0%): 这是最关键的部分. 用户与 Claude 之间的对话历史
    • 38k 说明目前已经进行了较深入的交流
  • Free space (44.8%): 剩余可用的净空间
  • Autocompact buffer (22.5%): 这是一个"安全垫"
    • 当用户的对话(Messages)占用到这个区域时, Claude Code 会自动执行 /compact, 压缩之前的对话以腾出空间

(2) MCP tools:

这里列出了笔者集成的MCP工具, 主要就是 GitHub 工具插件

Bash
1
2
3
4
5
mcp__github__create_or_update_file: 251 tokens
mcp__github__search_repositories: 155 tokens
mcp__github__create_repository: 158 tokens
mcp__github__get_file_contents: 173 tokens
# ...
  • 每一行都是一个特定的 API 功能, 以及它在上下文中占用的 token 数量
  • Token 消耗来源: 为了让 Claude 知道什么时候该用这些工具, 系统必须把每个工具的“说明书”(输入参数、返回类型等)放入上下文
  • ⚠️⚠️ 注意 ⚠️⚠️
    • 如果用户不经常使用 GitHub 插件, 断开这些MCP可以节省这 5.1k 的空间
    • 做法: /mcp -> github · ✔ connected 选中 -> 3. Disable
    • alt text

(3) Custom agents: Project + Plugin

  • Project: 我自己定义的一些子代理 (详见下文, "使用子代理实施"两步走Coding")
  • Plugin: 插件市场下载的一些插件. 目前占用很小, 主要是插件的描述信息

(4) Skills: Plugin

Skills 是 Claude Code 的一个高级功能, 允许用户定义特定的“技能”或“行为模式” (是 Claude Code 的一个特性, 允许它记住复杂的任务流)

详情参考 Claude Code - Skills, 可以简单理解成 "任务流水线"

  • Token 消耗来源: 用户定义的各种开发流程说明 (如 Hook Development, MCP Integration 等)
  • 这些技能相当于给 Claude 提供了额外的“知识库”, 让它在处理特定任务时更专业

节约地管理上下文

(1) 每做完一个功能点, 使用 /compact:

  • 作用: "智能压缩"
    • 保留内容: 文件上下文, 项目结构, 配置设置, 工具
    • 对话摘要: 压缩保留
  • 特点:
    • 可以手动运行(强烈推荐!)
    • 当上下文窗口达到 95% 满或剩余 25% 时自动触发
    • 有 "microcompact" 功能自动清理旧工具调用
  • 场景:
    • 在同一任务上继续工作
    • 需要保留之前的决策和上下文
    • 减少 token 但不想丢失重要信息
  • 效果: 就像清空了 "claude" 的 "cache", 只保留持久化数据, 大幅降低后续对话的 Token 消耗

对比一下 compact 前后的上下文使用情况:

alt text

(2) 每开一个新项目, 使用 .claudeignore:

  • 作用: 类似 .gitignore, 告诉 Claude 绝对不要读取哪些文件
  • 操作: 在项目根目录创建 .claudeignore, 然后写入"想要claude忽略的文件"即可
    • 笔者常用的“剔除对象”: node_modules, package-lock.json, yarn.lock, pnpm-lock.yaml, X.log, build, logs, X.csv ...
Danger

Claude Code 有时为了理解项目, 会尝试读取目录下所有文件

如果它不小心读了你的 package-lock.json (几万行) 或者一个 50MB 的 access.log, 5 小时额度可能瞬间蒸发...

(3) 每当任务切换时, 使用 /clear:

  • 作用: "完全清空"
    • 保留内容: 文件上下文, 项目结构, 配置设置, 工具
    • 删除内容: 对话历史
  • 适用场景:
    • 切换到完全不同的任务
    • 完成一个重要功能或修复后
    • 响应速度变慢时
  • 效果: 比 /compact 更彻底, 从零开始, 最省额度

VSCode 中使用 Claude-code

使用的前提是, 先在插件市场下载安装claude-code-plugin

u1s1, 感觉没啥要说明的, 跟在CLI里一模一样...

Claude Code GitHub Actions (with API)

"CC in GHA"

功能:

将 claude 这个命令行工具集成到你的 CI/CD 流水线中, 让 AI 自动完成代码审查、生成 PR 描述、甚至自动修复 Bug 😍

参考:

看看伯克利近期的巨著 LEANN 的 PR区/contributor区, 你就能明白 claude-code 在 GHA 中的威力了 😄

步骤:

非常简单, 就是在 GitHub Actions 的虚拟环境(Runner)里:

  1. 安装 Node.js 环境
  2. 通过 npm 安装 claude-code
  3. 注入 ANTHROPIC_API_KEY
  4. 运行 claude 命令处理你的代码

随便在 open-source 里找一个项目, 看看它们的模板咋写的就行 :)

pro订阅用户不能使用!

其实可以使用! 因此这一部分warning直接作废 (2026-01-10)!!!

Claude API (用于 GHA)Pro 订阅 (用于 Web/CLI 登录) 通常是分开计费的

Claude Pro 订阅用户无法获得 API_KEY, 因此无法使用 CC in GHA.

假如你又氪金充了 Claude API, 那么你就可以使用 CC in GHA, 但是要小心!

API Key 计费陷阱:

  1. GHA 里无法进行浏览器登录, 所以必须使用 ANTHROPIC_API_KEY
  2. GHA 里跑的每一次 Claude,都是在烧你充值进去的 API 余额,而不是你的 $20 月费
  3. 切记1: 不要在 GHA 里无限制地跑
  4. 切记2: 在触发条件里排除 bot 的提交, 或者只使用 workflow_dispatch (手动按钮触发)

ccusage 看看 token 使用情况

很多时候我们会想, claude pro 不按 token 计费, 到底能帮我们个人开发者省多少

这时候, 最好的方法是:

  1. 看看自己一个月用的token情况
  2. \(cost = {model1}{price} * {token usage}_1 + {model2}{price} * {token usage}_2\)

好消息是: 已经有一个开源仓库帮我们完成这些了!

ccusage @github

Bash
1
2
3
4
5
6
# 安装
npm install -g ccusage
# Show daily report (default)
ccusage
# Monthly aggregated report
ccusage monthly

比如, 这里粘贴一下我的使用情况:

alt text

我用 $20 的月费, 在这三天里 (写本文是订阅服务的第三天) 享受了价值 $14.44 的服务

这说明赚大了! 三天就回本了 70% 😍

如果按这个强度用一个月, 相当于用 $20 撬动了 $150+ 的 API 资源 🐛🐛🐛

使用子代理实施"两步走Coding"

Motivation:

很多时候我们在维护大型代码框架时, 希望ai能:

  1. 正确理解我们的问题
  2. 正确理解代码库的架构/模块/风格/逻辑
  3. 正确输出符合我们要求的代码

而claude本身有很多模型, 每个模型都有自己的强项, 比如:

  1. Opus 4.5: 最强的理解/逻辑/分析/推导/规划能力, 极其适合阅读和分析代码
  2. Sonnet 4.5: 最强的代码生成能力, 极其适合输出高质量代码

因此我们非常希望, 当我们将代码任务交付给AI时, 能够:

  1. Opus 4.5 来帮我们分析和理解代码
  2. Sonnet 4.5 来帮我们生成代码

Implementation:

做法很简单, 利用 claude 的子代理功能 (Sub-agent)

Bash
1
2
3
4
5
6
7
8
9
claude
# 进入claude console:
/agents
# 选择: Create new agent
Choose location
1. Project (.claude/agents/) # 我选择的是这个, project-level
2. Personal (~/.claude/agents/)
# 选择: Create with Claude (recommended)
1. Generate with Claude (recommended)

将自己的提示词告诉claude:

Markdown
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
当我们正在处理代码有关的内容时, 希望ai能:

1. 正确理解我们的**问题**
2. 正确理解**代码库**的架构/模块/风格/逻辑
3. **正确输出**符合我们要求的代码

而claude本身有很多模型, 每个模型都有自己的强项, 比如:

1. `Opus 4.5`: 最强的理解/逻辑/分析/推导/规划能力, 极其适合阅读和分析代码
2. `Sonnet 4.5`: 最强的代码生成能力, 极其适合输出高质量代码

因此我们非常希望, 当我们将代码任务交付给AI时, 能够:

1.`Opus 4.5` 来帮我们分析和理解代码
2.`Sonnet 4.5` 来帮我们生成代码

因此我希望定义一个 "两阶段" 代码生成流程, 先用 Opus 4.5 理解并分析规划, 然后用 Sonnet 4.5 来生成代码

随后就可以发现claude会帮我们创建一个子代理:

alt text

检查一下子代理 dual-model-coder 的内容 (vim .claude/agents/dual-model-coder.md)
Markdown
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
---
name: dual-model-coder
description: "Use this agent when the user requests help with coding problems, algorithm development, system design, or any task that involves both high-level technical planning and code implementation. This agent should be invoked proactively whenever a coding task requires strategic thinking followed by execution.\\n\\nExamples:\\n\\n<example>\\nContext: User asks for help implementing a complex feature\\nuser: \"I need to build a rate-limiting middleware for my API that supports multiple strategies\"\\nassistant: \"I'm going to use the Task tool to launch the dual-model-coder agent to help you design and implement this rate-limiting middleware.\"\\n<commentary>\\nThis is a coding problem that benefits from strategic planning (choosing the right rate-limiting approach, designing the architecture) followed by implementation, so the dual-model-coder agent should be used.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: User presents an algorithmic challenge\\nuser: \"How would I optimize this search function to handle millions of records?\"\\nassistant: \"Let me use the dual-model-coder agent to analyze this optimization problem and develop a solution.\"\\n<commentary>\\nThis requires both high-level thinking about optimization strategies and concrete code implementation, making it perfect for the dual-model-coder agent.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: User asks about refactoring existing code\\nuser: \"This function is getting too complex, can you help me refactor it?\"\\nassistant: \"I'll use the Task tool to launch the dual-model-coder agent to plan and execute this refactoring.\"\\n<commentary>\\nRefactoring requires strategic planning about code organization and design patterns, followed by implementation, so the dual-model-coder should handle this.\\n</commentary>\\n</example>"
model: opus
---

You are an elite software engineering agent that leverages a two-phase approach to solve coding problems with both strategic depth and implementation excellence.

## Your Dual-Phase Methodology

For every coding task, you will operate in two distinct phases:

**Phase 1: Strategic Planning (Using Claude Opus 4.5)**
In this phase, you focus on high-level thinking, architecture, and solution design:
- Analyze the problem thoroughly and identify core requirements
- Consider multiple approaches and evaluate trade-offs
- Design the optimal solution architecture
- Plan the implementation strategy, including edge cases and error handling
- Break down complex problems into manageable components
- Identify potential pitfalls and optimization opportunities
- Draft pseudocode or high-level outlines when helpful
- Make architectural decisions about patterns, data structures, and algorithms

When entering Phase 1, explicitly state: "**Phase 1: Strategic Planning with Opus 4.5**"
**Phase 2: Implementation (Using Claude Sonnet 4.5)**
In this phase, you focus on writing clean, efficient, production-ready code:
- Translate the strategic plan into concrete implementation
- Write well-structured, idiomatic code following best practices
- Include comprehensive error handling and input validation
- Add clear comments for complex logic
- Ensure code is maintainable and follows established patterns
- Implement the solution efficiently based on the planned approach
- Write code that handles edge cases identified in Phase 1

When entering Phase 2, explicitly state: "**Phase 2: Implementation with Sonnet 4.5**"

## Operational Guidelines

1. **Always use both phases**: Even for seemingly simple problems, conduct at least brief strategic planning before implementation

2. **Clear phase transitions**: Make it obvious when you're switching from planning to implementation

3. **Maintain consistency**: Ensure the implementation faithfully executes the plan developed in Phase 1

4. **Iterative refinement**: If the implementation reveals issues with the plan, acknowledge this and revisit Phase 1 as needed

5. **Context preservation**: Carry forward all decisions, constraints, and insights from Phase 1 into Phase 2

6. **Justification**: Briefly explain key architectural decisions during Phase 1 so the reasoning is clear

7. **Quality assurance**: After implementation, verify that the code:
    - Solves the stated problem completely
    - Handles edge cases identified during planning
    - Follows the architectural decisions made in Phase 1
    - Is production-ready and maintainable

8. **Proactive clarification**: If requirements are ambiguous, ask clarifying questions before beginning Phase 1

## Output Format

Structure your responses as:

**Phase 1: Strategic Planning with Opus 4.5**
[Analysis, approach evaluation, architectural decisions, implementation plan]

**Phase 2: Implementation with Sonnet 4.5**
[Clean, well-commented code that executes the plan]

**Summary**
[Brief overview of the solution and any important notes]

You represent the best of both worlds: the deep strategic thinking of Opus combined with the precise implementation capabilities of Sonnet. Use this dual-model approach to deliver solutions that are both architecturally sound and excellently implemented.

MCP Server 管理 github

MCP (Model Context Protocol) 允许 Claude 直接操作你的 GitHub 仓库。按照以下三个步骤即可完成安装与验证:

(1) 安装与配置

使用 claude mcp add 命令添加服务器。你需要提供一个具有相关权限的 GitHub Personal Access Token (获取token步骤)

Bash
1
2
3
4
5
claude mcp add -e GITHUB_PERSONAL_ACCESS_TOKEN=你的TOKEN -s user github -- npx -y @modelcontextprotocol/server-github

# -e: 设置环境变量(此处用于存放 Token)
# -s user: 将配置保存在用户级配置文件中
# --: 之后跟随的是启动该服务器的具体命令

(2) 查看已安装列表

安装完成后,你可以使用以下命令确认 GitHub MCP 是否已成功加载:

Bash
1
claude mcp list

该命令会列出所有当前活跃的 MCP 服务器及其运行状态

alt text

(3) 获取详细信息与工具集

如果你想查看 GitHub 插件具体提供了哪些“超能力”(创建 Issue、提交代码等), 请运行:

Bash
1
claude mcp get github

这会展示该服务器定义的 26 个工具详情及其所需的参数格式

(4) MCP 工具的开关 (影响上下文空间)

Bash
1
2
3
claude
/mcp
# 选择 Enable 或者 Disable 即可

alt text

(5) 日常使用

直接把 GitHub 相关的操作交给 claude 即可, 它会自动调用 MCP 工具完成任务, 就像你的私人助理一样 😍

alt text

Claude Code GitHub Actions (with subscription)

在 github issue/PR 中使用 claude-code bot

之前我记得自己写过一篇文章(其实就是本文上半部分), 介绍如何在 github issue/PR 里使用 claude-code bot. 当时说:

"claude API可以使用, claude pro订阅不可以, 因为没有 API_KEY"

这里来打个脸, claude pro订阅用户也可以!

Implementation:

使用 Claude Code GitHub Actions:

  • 即时 PR 创建:描述您需要什么,Claude 会创建一个包含所有必要更改的完整 PR
  • 自动化代码实现:通过单个命令将问题转化为可工作的代码
  • 遵循您的标准:Claude 尊重您的 CLAUDE.md 指南和现有代码模式

只需打开 claude 并运行 /install-github-app 即可

效果:

alt text

alt text