2026 年 Claude Code 完全使用教程:从入门到精通
AI 编程45 min read2026/3/6

2026 年 Claude Code 完全使用教程:从入门到精通

通过这篇全面的教程掌握 Claude Code。学习安装配置、核心命令、工作流、MCP 集成和高级技巧,全面提升你的 AI 编程效率。

两年前,AI 编程助手还住在你的 IDE 里——自动补全几行代码,偶尔给出正确的建议。到了 2026 年,游戏规则已经彻底改变。Claude Code 直接抛弃了 IDE 的辅助轮,搬进了你的终端,它可以读取整个代码库、跨项目编辑文件、运行命令、创建提交,甚至打开 Pull Request——全部通过自然语言指令完成。

无论你是想将工作效率提升 10 倍的资深开发者,还是刚开始接触 AI 编程的新手,这篇指南带你全面了解 Claude Code 的一切。读完这 45 分钟的内容,你将从安装配置一路掌握到高级自动化工作流,每一步都有真实示例。

TL;DR

Claude Code 是 Anthropic 的终端原生智能代理式(Agentic)编程工具。它能理解你的整个代码库,编辑多个文件,运行终端命令,管理 Git 工作流,并通过 MCP 集成外部工具——全部通过自然语言完成。本指南覆盖安装配置、核心命令、工作流、CLAUDE.md 配置、MCP 集成、安全管理和高级自动化技巧。

你将学到:

  • 如何在任意平台安装和配置 Claude Code
  • 必备命令和快捷键
  • 核心工作流:编码、调试、测试、Git 和 PR 创建
  • 高级功能:CLAUDE.md、自定义命令、MCP、Headless 模式
  • 安全和权限管理
  • 成本优化策略
  • Claude Code 与 CursorGitHub Copilot 等工具的对比

前置条件:

  • 一个终端或命令行
  • 基本的命令行使用经验
  • Claude 订阅(Pro、Max、Teams 或 Enterprise)或 Anthropic Console 账号
  • 一个代码项目

各章节预估时间:

章节 时间
安装与配置 5 分钟
必备命令 5 分钟
核心工作流 15 分钟
高级功能 10 分钟
权限与安全 5 分钟
实战案例 5 分钟

Claude Code 是什么?为什么你应该关注它?

在深入教程之前,先搞清楚 Claude Code 和市面上其他 AI 编程工具的本质区别。

Claude Code 是 Anthropic 的智能代理式编程工具——"智能代理式(Agentic)"这个词是关键。不同于传统的代码助手根据光标位置给出建议,Claude Code 作为一个自主代理运行。你用自然语言描述想要什么,它自己规划方案:读哪些文件、做什么修改、运行哪些命令、按什么顺序执行。

工作原理

Claude Code 的核心是一个代理循环

  1. 你提出任务——用自然语言描述
  2. Claude 分析——读取代码库中的相关文件
  3. Claude 规划——制定执行方案(你可以在 Plan Mode 中审查)
  4. Claude 执行——编辑文件、运行命令、创建提交
  5. 你审查确认——批准或拒绝修改

这个循环在你的终端中运行,Claude 直接访问你的文件系统和命令行——当然,在你设定的权限范围内。

核心差异

特性 Claude Code 传统 AI 助手
运行环境 终端原生 IDE 插件
上下文 读取整个代码库 当前文件 + 有限上下文
编辑 多文件自主编辑 单文件建议
命令 执行终端命令 无终端访问
Git 完整 Git 工作流自动化 有限或无
可扩展性 MCP、Hooks、自定义命令 插件市场

优势与不足

  • 读取并理解整个项目结构
  • 单次操作编辑多个文件
  • 直接运行测试、构建命令和脚本
  • 自动化 Git 工作流(提交、分支、PR)
  • 支持 6 个平台:终端、VS Code、JetBrains、桌面应用、Web、Slack
  • 通过 MCP、Hooks 和自定义命令扩展
  • 支持 Git Worktrees 并行会话
  • 需要付费订阅(终端使用无免费版)
  • 终端优先的 UX 对非 CLI 用户有学习曲线
  • 大型代码库的 Token 消耗可能较高
  • 需要网络连接(无离线模式)
  • 目前仍在活跃开发中——功能变化快

定价概览

计划 价格 适合人群
Pro $20/月 个人开发者,轻度使用
Max (5x) $100/月 常规用户,中等日使用量
Max (20x) $200/月 重度用户,高日使用量
Teams $30/用户/月 中小团队
Enterprise 定制 有安全需求的大型组织
API (Console) 按量付费 CI/CD、自动化、定制集成

你也可以通过 Amazon BedrockGoogle Vertex AIMicrosoft Foundry 使用 Claude Code,如果你的组织使用这些云服务商的话。

谁适合使用 Claude Code?

Claude Code 不适合所有人——这是有意为之。以下是最能从中获益的人群:

非常适合
  • 后端开发者——大部分时间在终端工作
  • 全栈工程师——构建跨多个文件和层级的功能
  • DevOps/平台工程师——需要自动化重复性任务
  • 技术负责人——审查 PR、管理 Git 工作流、维护代码质量
  • 开源维护者——需要处理 Issue 和生成文档
不太适合
  • 设计师——主要需要视觉设计工具(可以试试 Figma AIFramer
  • 非技术用户——需要无代码解决方案
  • 纯移动端用户——无法经常使用终端(虽然 Remote Control 有所帮助)

安装与配置

让 Claude Code 运行起来大约需要 5 分钟。以下是各平台的安装方法。

系统要求

  • macOS:10.15 Catalina 或更高版本
  • Linux:Ubuntu 20.04+、Debian 10+ 或同等版本
  • Windows:Windows 10+ 搭配 WSL2,或通过原生安装程序
  • Node.js:原生安装不需要(自包含二进制文件)
第 1 步:安装 Claude Code

选择适合你系统的安装方式:

macOS / Linux(推荐——原生安装):

curl -fsSL https://claude.ai/install.sh | bash

Windows (PowerShell):

irm https://claude.ai/install.ps1 | iex

Windows (CMD):

curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

macOS 通过 Homebrew:

brew install --cask claude-code

Windows 通过 WinGet:

winget install Anthropic.ClaudeCode

验证安装:

claude --version
第 2 步:认证登录

首次启动 Claude Code:

claude

系统会提示你登录,选择认证方式:

  • Claude Pro/Max/Teams/Enterprise(推荐)——使用 claude.com 账号登录
  • Anthropic Console——使用预付费 API 额度。系统会自动创建"Claude Code"工作区用于成本追踪
  • 第三方云服务——Amazon Bedrock、Google Vertex AI 或 Microsoft Foundry

如果之后需要切换账号:

/login
第 3 步:启动首次会话

进入项目目录并启动:

cd /path/to/your/project
claude

Claude Code 将启动交互式会话。你会看到一个可以输入自然语言指令的提示符。

试试你的第一个命令:

what does this project do?

Claude 会扫描项目结构,读取关键文件,然后给你一个总结。其他有用的入门命令:

explain the folder structure
what technologies does this project use?
where is the main entry point?
IDE 集成

Claude Code 也可以在 IDE 中使用。安装对应扩展:

  • VS Code / Cursor:在扩展市场搜索"Claude Code",或按 Cmd+Shift+P → "Claude Code: Open"
  • JetBrains:从市场安装 Claude Code 插件
  • 桌面应用:从 claude.com 下载 macOS 或 Windows 版本
  • Web:访问 claude.ai/code 在浏览器中使用

所有界面共享同一引擎——你的 CLAUDE.md 文件、设置和 MCP 服务器在所有平台通用。

虽然 Claude Code 现在支持 Windows 原生安装,但在 macOS 和 Linux 上体验最佳。Windows 用户建议在 WSL2(Windows Subsystem for Linux)中运行 Claude Code,以获得与 Unix 工具链和 Shell 命令的完全兼容。原生 Windows 安装程序可以满足基本使用,但某些高级功能如 Git Worktrees 和部分 MCP 服务器在 Windows 上可能存在边缘情况。

在 WSL2 中安装:

# 在 WSL2 终端中
curl -fsSL https://claude.ai/install.sh | bash

验证安装

继续之前,确认一切正常:

# 检查安装
claude --version

# 检查认证
claude -p "say hello"

# 检查项目访问
cd /path/to/your/project
claude -p "list the top-level files in this project"

如果三个命令都成功,你就可以开始使用 Claude Code 进行实际工作了。如果遇到问题,在 Claude Code 会话中运行 /doctor 获取自动诊断。


入门:必备命令

安装完成后,来掌握你每天都会用到的命令。

启动模式

# 交互模式——开始对话
claude

# 快速任务——执行单个任务后返回
claude "fix the build error in src/app.ts"

# 打印模式——非交互式,输出到 stdout
claude -p "explain the authentication flow"

# 继续上次会话
claude -c

# 恢复会话选择器
claude -r

# 带初始任务启动
claude commit

斜杠命令

在交互会话中,斜杠命令控制 Claude Code 的行为:

命令 说明
/help 显示所有可用命令
/clear 清空对话上下文
/compact 压缩上下文以节省 Token
/status 显示当前会话状态
/cost 显示 Token 使用量和费用
/login 切换认证方式
/model 切换 AI 模型
/agents 查看和管理子代理
/hooks 配置自动化 Hooks
/review 审查最近的代码变更
/pr-comments 处理 PR 审查评论
/init 为项目初始化 CLAUDE.md
/terminal-setup 配置终端集成
/doctor 诊断常见问题
/teleport 将 Web/移动端会话拉到终端
/desktop 将会话转移到桌面应用

快捷键

快捷键 操作
? 显示所有快捷键
Tab 命令/文件自动补全
命令历史
/ 打开命令面板
Ctrl+O 切换深度思考模式
Ctrl+C 取消当前操作
Esc 关闭、返回

理解权限提示

当 Claude Code 要执行可能修改系统的操作时,你会看到这样的权限提示:

Claude wants to run: npm test
Allow? [y]es / [n]o / [a]lways allow / [d]eny always

各选项含义:

  • y(yes)——本次允许。Claude 继续执行,下次还会再问。
  • n(no)——阻止此操作。Claude 会尝试替代方案。
  • a(always allow)——在当前会话中自动批准此类操作。适合 npm test 等重复命令。
  • d(deny always)——永久阻止此操作模式。适合你永远不想运行的破坏性命令。

权限系统是你的安全网。刚开始使用时,花点时间仔细阅读每个提示再批准。随着你对 Claude Code 在项目中的行为建立信任,可以在 .claude/settings.json 中预配置允许列表(详见权限与安全章节)来跳过安全命令的提示。

加速审批

对于你信任的命令(如运行测试、代码检查或 Git 操作),使用"always allow"选项。这能大幅加速工作流而不牺牲安全性。你也可以在项目设置中预配置:

{
  "permissions": {
    "allow": ["Bash(npm test)", "Bash(npm run lint)", "Bash(git *)"]
  }
}
进阶技巧:@ 文件引用

在提示词中用 @ 前缀引用特定文件或目录:

Explain the logic in @src/utils/auth.js
What's the structure of @src/components?
Compare @package.json and @package-lock.json

使用 @ 引用时,Claude 会自动加载该文件所在目录及父目录中的 CLAUDE.md 文件作为额外上下文。


核心工作流:你每天都会用到的功能

这是 Claude Code 真正发挥价值的地方。让我们逐一了解占日常使用 90% 的五个工作流。

工作流 1:编写与生成代码

最常见的用例——描述你想要什么,Claude 来构建。

简单函数生成:

create a utility function that validates email addresses using regex,
handles edge cases, and includes JSDoc documentation

多文件功能实现:

1. create a new database table for user profiles
2. create an API endpoint to get and update user profiles
3. build a webpage that allows users to see and edit their information

Claude 会:

  1. 分析你现有的项目结构和约定
  2. 创建或修改多个文件
  3. 展示变更的 diff
  4. 等待你批准后再写入

全栈功能——数据库、API 和 UI:

Build a complete "user notifications" feature:
1. Create a notifications table in the database with columns:
   id, user_id, type, title, message, read, created_at
2. Create a NotificationService in src/services/ with methods:
   create, markAsRead, getUnread, getAll
3. Add REST endpoints: GET /api/notifications, PATCH /api/notifications/:id/read
4. Build a notification bell component in React that shows unread count
   and a dropdown with the latest 10 notifications
5. Add WebSocket support so new notifications appear in real-time
6. Write tests for the service and API layers

这种多层级的提示正是 Claude Code 的 Agentic 方式真正超越自动补全工具的地方。Claude 会规划跨数据库、后端和前端层的整个功能,确保层与层之间的一致性——这在逐文件生成代码时很难做到。

为重复模式生成模板代码:

I need CRUD endpoints for these 4 resources: products, categories, reviews, and wishlists.
Follow the exact same patterns as the existing users resource in @src/routes/users.ts,
@src/services/userService.ts, and @src/repositories/userRepository.ts.
Include validation, error handling, and pagination for list endpoints.

Claude 读取一次参考实现,然后将相同模式应用四次——为每个资源调整表名、字段类型和验证规则。这比手动复制粘贴和修改模板代码要快得多。

要具体,不要模糊

你提供的细节越多,输出效果越好。不要说"add authentication",而是:

add JWT-based authentication using the existing Express app in src/server.ts.
Use bcrypt for password hashing, create a /api/auth/login and /api/auth/register endpoint,
and store tokens in HTTP-only cookies. Follow the patterns in @src/routes/users.ts

使用 @ 引用现有文件,帮助 Claude 匹配你项目的模式。

工作流 2:理解与浏览代码

当你加入新项目或探索不熟悉的代码时,Claude Code 就是你的向导。

获取项目概览:

what does this project do?
explain the architecture and key design decisions

追踪执行流程:

trace the request flow from when a user clicks "Submit Order"
to when the order confirmation email is sent

查找相关代码:

find all places where we handle user authentication
where is the database connection configured?
which components use the useAuth hook?

Claude 使用代理式搜索来探索你的代码库——它不只是简单地 grep 字符串。它读取 import 语句,跟踪函数调用,理解文件之间的关系。

深入理解特定文件:

explain @src/middleware/auth.ts line by line.
What edge cases does this code handle? What could go wrong?

比较实现方式:

compare the error handling approach in @src/routes/users.ts
vs @src/routes/orders.ts. Which is better and why?

这在加入新团队时特别强大——不用花几天时间阅读代码,你可以和 Claude 就架构、模式和潜在问题进行引导式对话。

工作流 3:修复 Bug

Bug 修复是 Claude Code 真正闪光的地方。与其花 30 分钟追踪堆栈跟踪,直接粘贴错误信息让 Claude 处理。

分享错误信息:

I'm seeing this error when running npm test:

TypeError: Cannot read properties of undefined (reading 'map')
    at UserList (/src/components/UserList.tsx:15:23)
    at renderWithHooks (/node_modules/react-dom/...)

Claude 会:

  1. 读取堆栈跟踪中提到的文件
  2. 理解周围上下文
  3. 定位根本原因
  4. 提出带解释的修复方案
  5. 在你批准后应用修复

即使你使用中文工作环境,也要将错误信息以英文原文粘贴。这有助于 Claude 精确匹配错误模式,也方便你后续搜索解决方案。

自动重现并修复:

run npm test, find any failing tests, and fix them

Claude 会执行测试套件,解析输出,识别失败,读取相关源代码,应用修复——迭代直到测试全部通过。

逐步调试复杂问题:

The checkout page shows a blank screen on mobile devices but works fine on desktop.
1. Check the responsive CSS and media queries in the checkout components
2. Look for any JavaScript errors that might be viewport-dependent
3. Check if any third-party scripts block rendering on mobile
4. Suggest and apply fixes

从 Git diff 中修复:

review the changes in my last commit and check if I introduced any bugs

Claude 读取 diff,将变更代码与代码库其余部分交叉引用,标记潜在问题——捕捉自动化 Linter 遗漏的空值检查、损坏的导入或逻辑错误。

工作流 4:测试

Claude Code 可以从头构建整个测试套件,或填补现有覆盖率的空白。

查找未测试的代码:

find functions in the auth module that don't have test coverage

生成测试:

write comprehensive unit tests for src/services/payment.ts
including edge cases and error scenarios

测试驱动开发:

1. write a failing test for a function that calculates shipping costs
   based on weight, distance, and delivery speed
2. implement the function to make the test pass
3. add edge case tests for invalid inputs
4. run all tests and fix any failures

Claude 自然地遵循红-绿-重构循环。先写测试,实现最小代码使测试通过,然后重构。

集成和端到端测试:

write integration tests for the user registration flow that test:
1. successful registration with valid data
2. duplicate email rejection
3. weak password rejection
4. email verification token generation
Use the existing test database setup in @tests/setup.ts

覆盖率分析:

analyze the test coverage for the src/services/ directory.
Which functions have no tests? Which have only happy-path tests?
Prioritize by risk and suggest which tests to add first.

Claude 还可以运行你的覆盖率工具(如 istanbulc8),解析输出,然后专门针对未覆盖的分支和边缘情况生成测试。

工作流 5:Git 与 Pull Request

Claude Code 处理完整的 Git 工作流——从暂存变更到创建 Pull Request。

智能提交:

commit my changes with a descriptive message

Claude 分析 diff,理解变更的语义含义,生成有意义的提交信息——不只是"update files"。

分支管理:

create a new branch called feature/user-profiles
what files have I changed?
show me the last 5 commits
help me resolve merge conflicts

创建 Pull Request:

create a pr

Claude 会:

  1. 汇总所有文件的变更
  2. 生成描述性的 PR 标题和正文
  3. 包含变更内容和原因的上下文
  4. 使用 gh pr create 将 PR 推送到 GitHub

从 PR 开始代码审查:

# 从已有 PR 启动 Claude
claude --from-pr 42

这会将 PR diff 作为上下文加载,让你审查、评论或请求修改。

处理 PR 审查评论:

/pr-comments

Claude 读取你已打开 PR 上的审查评论,帮你逐一处理——修改代码、回复反馈、推送更新。

Cherry-pick 和 Backport:

cherry-pick the fix from commit abc123 into the release/2.1 branch
and resolve any merge conflicts

Rebase 和整理历史:

interactive rebase the last 5 commits into 2 logical commits:
one for the database migration and one for the API changes

Claude 处理大多数开发者头疼的复杂 Git 操作——rebase、冲突解决和历史整理——并清楚地解释它在做什么以及为什么。

示例:完整的 Git 工作流

这是一个组合多个 Git 操作的典型会话:

> create a new branch called feature/add-search
> add fuzzy search to the product listing page using Fuse.js
> write tests for the search functionality
> run the tests and fix any failures
> commit my changes with a descriptive message
> create a pr with a detailed description

Claude 依次处理所有六个步骤,在整个工作流中保持上下文。


高级功能

掌握基础之后,这些功能将你的生产力提升到新的层次。

CLAUDE.md:项目的 AI 配置文件

CLAUDE.md 是提升 Claude Code 输出质量最有效的功能。它是一个 Markdown 文件,告诉 Claude 关于你项目的信息——每次会话开始时自动读取。

项目级 CLAUDE.md(项目根目录):

# Project: E-commerce API

## Tech Stack

- Node.js 20 + TypeScript 5.4
- Express.js with Zod validation
- PostgreSQL + Prisma ORM
- Jest for testing

## Coding Conventions

- Use functional components and hooks (no class components)
- All API responses follow the { data, error, meta } pattern
- Error handling uses custom AppError class in src/utils/errors.ts

## Commands

- `npm run dev` — start development server
- `npm test` — run all tests
- `npm run lint` — run ESLint
- `npm run build` — production build

用户级 CLAUDE.md~/.claude/CLAUDE.md):

# Personal Preferences

- Use TypeScript strict mode
- Prefer const over let
- Use early returns instead of nested if/else
- Write concise commit messages in conventional commit format
CLAUDE.md 最佳实践
  1. /init 开始——Claude Code 会根据你的项目生成初始 CLAUDE.md
  2. 要具体——"Use Prisma"不如"Use Prisma ORM with the schema at prisma/schema.prisma"有用
  3. 包含命令——告诉 Claude 如何运行测试、代码检查、构建和部署
  4. 记录模式——展示你的约定让 Claude 遵循
  5. 保持更新——随着项目演进添加新笔记
  6. 使用目录级文件——在子目录中添加 CLAUDE.md 提供特定于该区域的上下文

Hooks:基于事件的自动化

Hooks 让你在 Claude Code 中发生特定事件时运行自定义脚本。

通过交互菜单设置:

/hooks

可用的 Hook 事件:

事件 触发时机
permission_prompt Claude 请求执行权限
idle_prompt Claude 等待你的输入
auth_success 认证完成
elicitation_dialog Claude 需要额外信息

示例:Claude 需要关注时发送桌面通知(macOS):

osascript -e 'display notification "Claude Code needs your attention" with title "Claude Code"'

示例:长任务完成时播放提示音:

afplay /System/Library/Sounds/Glass.aiff

自定义斜杠命令(Skills)

你可以创建出现在 / 菜单中的可复用命令:

项目级自定义命令.claude/commands/review-pr.md):

Review the current PR changes for:

1. Security vulnerabilities (SQL injection, XSS, CSRF)
2. Performance issues (N+1 queries, missing indexes)
3. Error handling gaps
4. Test coverage for new code
5. Adherence to our coding standards in CLAUDE.md

Output a structured review with severity levels (critical/warning/info).

现在你可以在任何会话中运行 /review-pr,Claude 就会执行这个工作流。

子代理(Subagents)

Claude Code 可以为复杂任务生成专门的子代理:

> /agents

.claude/agents/ 中创建自定义子代理:

{
  "id": "api-designer",
  "description": "Designs RESTful API endpoints following our conventions",
  "tools": ["Read", "Grep", "Glob", "AskUserQuestion"],
  "systemPrompt": "You are an API design specialist..."
}

MCP(模型上下文协议)集成

MCP 是一个开放标准,让 Claude Code 连接到本地文件系统之外的外部工具和数据源。

在项目的 .mcp.json 中配置 MCP 服务器:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "your-token-here" }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": { "DATABASE_URL": "postgresql://localhost:5432/mydb" }
    }
  }
}

常用 MCP 服务器:

服务器 用途
server-github 访问 GitHub 仓库、Issue、PR
server-postgres 查询 PostgreSQL 数据库
server-filesystem 访问项目目录外的文件
server-slack 读取/发送 Slack 消息
server-puppeteer 浏览器自动化
MCP 安全

MCP 服务器以你的用户账号权限运行。小心处理数据库访问令牌和 API 密钥。将敏感值存储在环境变量中,而不是直接写在 .mcp.json 中。

Headless 模式与 CI/CD 集成

-p(print)标志启用非交互模式,非常适合自动化。

基本 Headless 用法:

# 分析函数
claude -p "explain the main function in src/index.ts"

# 生成代码并输出到文件
claude -p "generate a migration to add a status column to orders" > migration.sql

# 通过管道输入分析
git diff main | claude -p "review these changes for security issues"

GitHub Actions 集成:

name: Claude Code Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Claude Code
        run: curl -fsSL https://claude.ai/install.sh | bash
      - name: Review PR
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          git diff origin/main...HEAD | claude -p "Review this diff for bugs, security issues, and code style problems."

深度思考模式

对于需要更深层推理的复杂问题,切换深度思考模式:

  • 快捷键:会话中按 Ctrl+O
  • 适合复杂重构、架构决策、调试微妙的竞态条件等场景

Git Worktrees:并行会话

需要同时处理多个功能?使用 Git Worktrees:

# 在命名的 worktree 中启动 Claude
claude --worktree feature-auth

# 启动另一个并行会话
claude --worktree bugfix-123

每个 worktree 有自己的分支和工作目录,可以同时运行多个 Claude Code 会话而不冲突。

Plan Mode:安全分析

当你想让 Claude 只分析不修改时:

> use plan mode to analyze the database schema and suggest optimizations

Plan Mode 下,Claude 只能读取文件和提问——不能编辑文件或运行命令。适合架构审查、安全审计和学习新代码库。

跨设备工作流

从 Web 开始,在终端完成:

  1. claude.ai/code 或 iOS 应用中开始编程任务
  2. 回到桌面后,在终端中输入 /teleport
  3. Web 会话连同完整上下文转移到终端

转交到桌面应用进行可视化审查:

/desktop

Unix 风格管道与脚本

Claude Code 是一等公民 Unix 工具,支持管道输入输出:

# 查找 TODO 注释并排优先级
grep -rn "TODO" src/ | claude -p "prioritize these TODOs by severity"

# 生成迁移并保存
claude -p "generate a SQL migration to add indexes to the users table" > migration.sql

权限与安全

Claude Code 直接访问你的文件系统和终端——这正是它强大的原因。但这也意味着你需要理解权限系统。

权限模型

当 Claude Code 要执行操作(编辑文件、运行命令、访问网络)时,它会请求你的许可:

响应 行为
Allow once 允许此次特定操作
Allow always 自动批准此类操作
Deny 阻止此操作

在 settings.json 中配置权限

在项目的 .claude/settings.json 中进行更细粒度的控制:

{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "AskUserQuestion",
      "Bash(npm test)",
      "Bash(npm run lint)",
      "Bash(git *)"
    ],
    "deny": ["Bash(rm -rf *)", "Bash(curl *)", "WebFetch"]
  }
}

权限类别

类别 控制内容 默认
Read 读取文件内容 自动允许
Edit 修改文件 需要审批
Bash 运行终端命令 需要审批
WebFetch 发起 HTTP 请求 需要审批
MCP 使用 MCP 服务器工具 需要审批

安全最佳实践

  1. 从严格开始——只允许你实际需要的命令
  2. 谨慎使用通配符——Bash(git *)Bash(*) 安全
  3. 拒绝破坏性命令——始终拒绝 rm -rfDROP TABLE
  4. 审批前审查——在接受前阅读 Claude 提议的变更
  5. 审计使用 Plan Mode——审查敏感代码时使用 Plan Mode 防止修改
  6. 定期轮换 API 密钥——如果使用 MCP 连接外部服务

数据隐私考虑

  • 会话级处理——Claude Code 在活跃会话期间按需读取文件,不会上传整个代码库
  • 不用于模型训练——根据 Anthropic 的使用政策,付费计划处理的代码不用于模型训练
  • 本地执行——文件编辑和终端命令在你的本地机器上执行
  • 网络请求——只在你批准时才发起(通过 WebFetch 或 MCP 工具)
  • 企业级控制——Enterprise 计划提供审计日志、数据驻留选项和集中策略管理

实战案例:用 Claude Code 构建一个 CLI 工具

让我们用一个实际例子把所有知识串起来。我们将构建一个简单的 TODO 管理 CLI 工具——从初始化到一个可运行的、经过测试的应用。

第 1 步:项目初始化
mkdir todo-cli && cd todo-cli
claude

给 Claude 任务:

Initialize a new Node.js project with TypeScript for a CLI tool called "todo-cli".
Set up with TypeScript strict mode, Vitest for testing, Commander.js for CLI parsing,
and a src/ directory structure.
第 2 步:创建 CLAUDE.md
/init

然后增强生成的 CLAUDE.md,添加项目约定和命令说明。

第 3 步:实现核心功能
implement the core todo functionality:
1. add command - add a new todo with title and optional priority
2. list command - list all todos with filtering by status and priority
3. done command - mark a todo as completed by ID
4. remove command - delete a todo by ID
5. store todos in a local JSON file at ~/.todo-cli/todos.json

Claude 会创建多个文件:src/index.tssrc/commands/src/storage.tssrc/types.ts

第 4 步:编写测试
write comprehensive tests for all commands including edge cases
and the --json output format. Use an in-memory storage mock.
第 5 步:运行并修复测试
run all tests and fix any failures

Claude 执行测试,识别失败,修复问题——迭代直到全部通过。

第 6 步:完善功能
1. add colorful table output using chalk and cli-table3
2. add input validation with helpful error messages
3. update the README with installation and usage instructions
第 7 步:提交并发布
commit all changes with a descriptive message, then create a PR

结果:一个功能完整、经过测试的 CLI 工具——在一个 Claude Code 会话中构建完成。手动编码可能需要 2-3 小时的工作,使用 Claude Code 大约 15-20 分钟就能完成。

为什么这个工作流如此有效

  1. 声明式而非过程式——你描述想要什么,不用说明如何构建
  2. 迭代式完善——每一步都建立在前一步的基础上,Claude 保持上下文
  3. 测试先行验证——在完善之前先写测试,尽早发现问题
  4. CLAUDE.md 作为项目记忆——确保每个后续命令的输出与你的项目模式一致
  5. Git 作为安全网——频繁提交意味着随时可以回滚

技巧与最佳实践

提示词策略

要具体,不要模糊

❌ "fix the bug" ✅ "fix the TypeError in src/components/UserList.tsx where users array might be undefined when the API returns empty data"

提供上下文

❌ "add a feature" ✅ "add a search feature to the product listing page that filters by name and category, following the same patterns as @src/components/UserSearch.tsx"

使用分步指令

❌ "build the whole thing" ✅ "1. create the database schema 2. create the API endpoints 3. build the frontend components 4. write tests"

让 Claude 先探索

❌ 直接跳到"change X in file Y" ✅ "analyze the authentication flow first, then suggest improvements"——让 Claude 先理解再行动

上下文管理

  • 定期使用 /compact——压缩对话以节省 Token 同时保留关键上下文
  • 开启聚焦会话——一个任务一个会话,效果比马拉松式会话好
  • 明确引用文件——用 @filename 而非描述文件内容
  • 切换话题时用 /clear——换任务时清空上下文避免混淆

成本优化

策略 影响 方法
使用 Max 计划 无限使用消除 Token 焦虑
写具体提示词 减少来回交互
使用 /compact 压缩上下文减少 Token
批量处理相关任务 跨相关变更复用上下文
/cost 监控 了解消耗帮助调整行为

高级提示词模式

"先分析再行动"模式:

First, analyze the current authentication implementation in @src/auth/.
Then, identify any security vulnerabilities.
Finally, fix the issues you found, prioritizing by severity.

"参考实现"模式:

Look at how pagination is implemented in @src/routes/users.ts.
Now implement the same pagination pattern for @src/routes/products.ts
and @src/routes/orders.ts.

"约束优先"模式:

Refactor the payment service with these constraints:
- Must maintain backward compatibility with the existing API
- Must not change the database schema
- Must keep all existing tests passing

"文档驱动开发"模式:

1. Write the API documentation for a new /api/v2/notifications endpoint
2. Generate the implementation based on the documentation
3. Write tests that validate the implementation matches the docs
  1. 不要不看就批准——始终在接受前审查 Claude 的修改
  2. 不要忽略测试失败——如果 Claude 的变更破坏了测试,先修复再继续
  3. 不要跳过 CLAUDE.md——5 分钟的设置节省数小时的修正
  4. 不要使用过于宽泛的提示词——"Refactor everything"会产生不一致的结果
  5. 不要忘记频繁提交——小而频繁的提交使回滚更容易

Claude Code vs 竞品对比

功能对比

功能 Claude Code Cursor GitHub Copilot Windsurf Aider
运行环境 终端 + IDE + Web IDE(VS Code 分支) IDE 插件 IDE(VS Code 分支) 终端
Agentic 编辑 ✅ 完整 ✅ 完整 ✅ Agent 模式 ✅ 完整 ✅ 完整
多文件编辑
Git 自动化 ✅ 完整工作流 ⚠️ 基础 ⚠️ 基础 ⚠️ 基础 ✅ 良好
MCP 支持
CI/CD 模式 ✅ Headless ✅ Copilot CLI
免费版 ✅ 有限 ✅ 有限 ✅ 有限 ✅(自带密钥)
起步价 $20/月 $20/月 $10/月 $15/月 免费(API 费用)

选择 Claude Code 的场景

  • 你是终端优先开发者——Claude Code 为 CLI 用户而生
  • 你需要 Git 自动化——没有其他工具能匹配从分支到 PR 的端到端流程
  • 你需要多平台访问——终端、VS Code、JetBrains、桌面应用、Web、Slack
  • 你需要 CI/CD 集成——Headless 模式专为自动化管道设计

选择替代品的场景

  • 你想要可视化 IDE 体验——CursorWindsurf 提供更丰富的可视化 diff 和 GUI 工作流
  • 你预算有限——GitHub Copilot 从 $10/月起
  • 你更喜欢行内建议——Copilot 和 Cursor 在输入时的自动补全更流畅

Claude Code vs Cursor 深入对比

方面 Claude Code Cursor
UX 范式 对话驱动 混合——行内建议 + 聊天 + Composer
上下文窗口 按需读取,整个代码库可访问 索引代码库用于 @-mentions
多文件编辑 原生——Claude 规划并一次性跨文件编辑 Composer 模式——多文件编辑带可视化 diff
学习曲线 较陡——需要终端操作和提示词技巧 较缓——熟悉的 VS Code 界面加 AI 层
最适合 复杂重构、Git 自动化、CI/CD 实时编码辅助、可视化工作流
它们并不互斥

很多开发者同时使用 Claude Code 和 IDE 工具。例如,用 Cursor 获取实时行内建议,切换到 Claude Code 处理重构、测试生成或 PR 创建等大型任务。


常见问题

Claude Code 是什么?和 GitHub Copilot 有什么区别?

Claude Code 是 Anthropic 的智能代理式编程工具,在终端中原生运行,能读取整个代码库、编辑文件、通过自然语言执行命令。与 GitHub Copilot 主要在 IDE 中提供行内代码建议不同,Claude Code 作为完全自主的代理运行,能够进行多文件编辑、Git 工作流和终端命令执行。

Claude Code 是免费的吗?

需要付费订阅。可用 Claude Pro($20/月)、Max($100–200/月)、Teams($30/用户/月)或 Enterprise 计划。也可以通过 Anthropic Console 使用预付费 API 额度,或通过 Amazon Bedrock、Google Vertex AI、Microsoft Foundry 访问。

Claude Code 支持什么编程语言?

支持几乎所有编程语言,因为它以文本方式读取和编辑文件并执行终端命令。在 Python、JavaScript/TypeScript、Go、Rust、Java 和 C++ 等主流语言上表现优秀。

如何为项目设置 CLAUDE.md?

在项目根目录创建 CLAUDE.md 文件,写入项目特定指令。Claude Code 在每次会话开始时自动读取。运行 /init 可以生成一个初始文件。

什么是 MCP?

MCP(Model Context Protocol)是一个开放标准,让 Claude Code 连接外部工具和数据源。在项目的 .mcp.json 文件中配置 MCP 服务器,即可让 Claude 访问数据库、API、文档等。

能用在 CI/CD 流水线中吗?

可以。Claude Code 支持通过 -p 标志进行非交互式执行的 Headless 模式,可在 GitHub Actions、GitLab CI/CD 等流水线中使用。

如何控制成本?

使用 /cost 监控开支,/compact 压缩上下文,写具体的提示词减少交互,使用量大考虑 Max 计划。

处理私有代码安全吗?

Claude Code 提供细粒度权限控制。可以配置允许/拒绝列表,使用 Plan Mode 进行只读分析,Enterprise 计划有额外安全功能。代码按 Anthropic 的数据使用政策处理。

能和我的 IDE 配合使用吗?

可以。支持 VS Code、Cursor 和 JetBrains IDE 扩展,还有桌面应用和 Web 界面。所有界面共享同一引擎。

如何处理大型代码库?

Claude Code 使用代理式搜索智能浏览大型项目。它不会将整个代码库加载到内存中——而是按需读取文件、跟踪导入、使用类 grep 工具查找相关代码。对于超大型 monorepo,一个结构良好的 CLAUDE.md 能帮助 Claude 更高效地导航。


总结与下一步

你已经全面了解了 Claude Code 从安装到高级自动化的完整使用流程。

你学到了什么
  • 安装配置:5 分钟内在 macOS、Linux 或 Windows 上安装 Claude Code
  • 核心命令:交互模式、快速任务、打印模式和会话管理
  • 5 个日常工作流:代码生成、代码库导航、Bug 修复、测试和 Git 自动化
  • 高级功能:CLAUDE.md、自定义命令、子代理、MCP 集成、Headless 模式和 Git Worktrees
  • 安全管理:权限模型、设置配置和企业最佳实践
  • 优化策略:提示词策略、上下文管理和成本控制
  • 竞品对比:Claude Code 与 Cursor、GitHub Copilot、Windsurf 和 Aider 的定位

推荐下一步

  1. 从小处开始——选一个当前任务(修 Bug、写测试、创建 PR)用 Claude Code 试试
  2. 设置 CLAUDE.md——在主项目上运行 /init 并自定义
  3. 学习快捷键——在会话中按 ? 查看所有快捷键
  4. 尝试 MCP——连接一个外部工具(GitHub、数据库或 Slack)
  5. 探索自定义命令——创建 /review-pr/daily-standup 命令
  6. 加入社区——访问 Claude Code GitHub 仓库

继续学习

常见问题排查

问题 原因 解决方案
command not found: claude 安装不在 PATH 中 重新运行安装脚本或添加 ~/.local/bin 到 PATH
认证循环 Token 过期或网络问题 运行 /login 重新认证
Claude 找不到文件 工作目录错误 确保在项目根目录运行 claude
响应缓慢 上下文过大 使用 /compact 减少上下文
MCP 服务器启动失败 缺少依赖 手动运行 MCP 服务器命令检查错误

运行内置诊断:

/doctor

保持 Claude Code 更新

# 原生安装更新
curl -fsSL https://claude.ai/install.sh | bash

# Homebrew 更新
brew upgrade claude-code

# 检查版本
claude --version

本指南会随着 Claude Code 的发展定期更新。收藏此页面,随时查看最新功能、工作流和最佳实践。

最后更新:2026 年 3 月

标签:AI 编程AI 工具提示词工程AI 开发者工具技巧与窍门最佳实践
博客

相关内容