Claude Code 完整使用指南

适合新手阅读的 Claude Code 入门与进阶文档


目录

  1. 简介
  2. 基础用法
  3. 高阶用法
  4. 隐藏/高级技巧

简介

Claude Code 是 Anthropic 开发的 AI 编程助手,直接在终端中运行。它能够理解你的整个代码库,执行复杂的编程任务,并与其他工具无缝集成。

核心特点:

  • 🖥️ 终端原生运行,无需 IDE 插件
  • 📁 自动理解整个代码库上下文
  • 🔧 直接执行文件编辑和 Shell 命令
  • 🧩 支持 MCP 协议扩展能力
  • 🎯 支持多种编程语言和框架

基础用法

安装和启动

macOS / Linux
# 使用官方安装脚本
curl -fsSL https://claude.ai/install.sh | bash

# 或使用 Homebrew
brew install --cask claude-code
Windows
# PowerShell
irm https://claude.ai/install.ps1 | iex

# 或使用 WinGet
winget install Anthropic.ClaudeCode
VS Code 扩展
# 命令行安装
code --install-extension anthropic.claude-code

或从 VS Code Marketplace 安装。

JetBrains 插件

JetBrains Marketplace 安装。

启动 Claude Code
# 在项目目录中启动
cd your-project
claude

# 指定模型启动
claude --model claude-sonnet-4-20250514

# 以计划模式启动(只读,不执行写操作)
claude --permission-mode plan

# 恢复上次会话
claude --resume

基本命令和交互方式

内置斜杠命令 (Slash Commands)

输入 / 可以看到所有可用命令:

命令 用途
/help 显示帮助信息
/init 初始化项目,生成 CLAUDE.md
/clear 清除对话历史(别名:/reset, /new
/compact [instructions] 压缩对话,可选指定保留重点
/copy [N] 复制输出到剪贴板
/doctor 运行诊断检查
/context 可视化当前上下文使用情况
/permissions 管理权限设置
/model 切换模型
/config/settings 打开设置界面
/memory 打开项目的 CLAUDE.md 文件
/cost 显示当前会话费用
/bug 报告问题
/logout 退出登录
快速命令前缀
前缀 用途 示例
/ 执行斜杠命令或技能 /help
! 直接运行 Bash 命令 !npm test
@ 提及文件路径 分析 @src/auth.ts
多行输入
方式 快捷键
快速换行 \ + Enter
macOS 默认 Option + Enter
Shift+Enter Shift + Enter(部分终端支持)
控制序列 Ctrl + J
粘贴图片
  • Ctrl+V(或 macOS 上 iTerm2 的 Cmd+V,Windows 的 Alt+V):从剪贴板粘贴图片,会在光标处插入 [Image #N] 标记。

常见使用场景

代码调试
# 粘贴错误信息让 Claude 分析
I'm getting this error when running npm test:
Error: Cannot find module './utils'

或者直接用 ! 运行命令:

!npm test

错误输出会自动进入上下文,然后说 “帮我修复这个错误”。

代码重构
Refactor the auth module to use async/await instead of callbacks
解释代码
Explain how the payment flow works in this codebase
生成测试
Write unit tests for src/utils/dateHelpers.ts
创建新功能
Add a dark mode toggle to the settings page
Git 操作
Commit these changes with a descriptive message
Create a PR for this branch

高阶用法

配置选项和自定义

配置文件层级

Claude Code 配置文件按优先级排序:

层级 路径 用途
用户级 ~/.claude/settings.json 个人全局默认设置
项目级 .claude/settings.json 项目团队共享设置(提交到版本控制)
本地级 .claude/settings.local.json 项目个人设置(加入 .gitignore)
托管级 /etc/claude-code/ 企业级管理设置
配置示例
{
  "model": "claude-sonnet-4-20250514",
  "permissions": {
    "defaultMode": "default",
    "allow": [
      "Read(**)",
      "Edit(**)",
      "Bash(npm *)",
      "Bash(git *)"
    ],
    "deny": [
      "Read(.env*)",
      "Bash(rm -rf /*)"
    ]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write ."
          }
        ]
      }
    ]
  }
}
权限模式
模式 说明
default 默认模式 - 对未预授权的操作请求批准
acceptEdits 自动接受文件编辑,仍需确认 Shell 命令
plan 只读计划模式 - 不执行任何写操作
dontAsk 自动拒绝未预授权的操作
bypassPermissions 跳过所有权限提示(危险)

切换权限模式:按 Shift+Tab 或使用 /permissions 命令。

启动时指定权限模式:

claude --permission-mode plan
claude --dangerously-skip-permissions  # 跳过所有权限检查

与项目集成

CLAUDE.md 文件

CLAUDE.md 是项目的持久化记忆文件,Claude Code 在每个会话开始时自动加载。

位置选择:

范围 位置 用途
项目级 ./CLAUDE.md./.claude/CLAUDE.md 团队共享的项目指令
用户级 ~/.claude/CLAUDE.md 个人所有项目的偏好
本地级 ./CLAUDE.local.md 项目个人设置(添加到 .gitignore)

创建 CLAUDE.md:

运行 /init 自动生成,或手动创建:

# Project Overview
This is a Next.js e-commerce application.

## Build Commands
- Development: `npm run dev`
- Build: `npm run build`
- Test: `npm test`
- Lint: `npm run lint`

## Coding Standards
- Use TypeScript strict mode
- Prefer functional components with hooks
- Follow ESLint and Prettier rules

## Project Structure
- `src/components/` - React components
- `src/lib/` - Utility functions
- `src/api/` - API routes
导入其他文件

在 CLAUDE.md 中使用 @ 语法导入其他文件:

# Project Info
See @README.md for project overview.
See @package.json for available commands.

## Additional Docs
- Git workflow: @docs/git-workflow.md
分类规则 .claude/rules/

为不同文件类型或目录设置特定规则:

.claude/
├── rules/
│   ├── api.md          # API 相关规则
│   ├── frontend.md     # 前端相关规则
│   └── tests.md        # 测试相关规则

工具调用和能力扩展

内置工具
工具 用途
Read 读取文件内容
Edit 编辑文件
Write 创建或覆盖文件
Bash 执行 Shell 命令
Grep 搜索文件内容
Glob 查找文件
WebFetch 抓取网页内容
权限规则语法

在 settings.json 中配置工具权限:

{
  "permissions": {
    "allow": [
      "Read(**)",                  // 允许读取所有文件
      "Edit(src/**)",              // 允许编辑 src 目录下文件
      "Bash(npm run *)",           // 允许 npm run 开头的命令
      "Bash(git commit *)",        // 允许 git commit
      "WebFetch(domain:github.com)" // 允许抓取 GitHub 域名
    ],
    "deny": [
      "Read(.env*)",               // 禁止读取 .env 文件
      "Bash(rm -rf /*)",           // 禁止危险命令
      "Edit(**/secrets/**)"        // 禁止编辑 secrets 目录
    ]
  }
}
MCP (Model Context Protocol) 服务器

MCP 是开放标准,让 Claude Code 连接外部工具和数据源。

添加 MCP 服务器:

# HTTP 服务器(推荐)
claude mcp add notion --transport http https://mcp.notion.com/mcp

# 带认证头的 HTTP 服务器
claude mcp add secure-api --transport http https://api.example.com/mcp \
  --header "Authorization: Bearer your-token"

# Stdio 服务器(本地工具)
claude mcp add filesystem --transport stdio -- npx -y @modelcontextprotocol/server-filesystem /path/to/dir

管理 MCP 服务器:

# 列出所有 MCP 服务器
claude mcp list

# 删除服务器
claude mcp remove notion

常用 MCP 服务器:

  • GitHub - 仓库和 PR 管理
  • Notion - 文档和知识库
  • Slack - 消息和通知
  • PostgreSQL - 数据库查询
  • Puppeteer - 浏览器自动化
Skills(技能)

Skills 是扩展 Claude 能力的模块化指令集。

创建技能:

# 创建个人技能目录
mkdir -p ~/.claude/skills/explain-code

创建 ~/.claude/skills/explain-code/SKILL.md

---
name: explain-code
description: Explains code with visual diagrams and analogies. Use when explaining how code works.
---

When explaining code, always include:

1. **Start with an analogy**: Compare the code to something from everyday life
2. **Draw a diagram**: Use ASCII art to show the flow
3. **Walk through the code**: Explain step-by-step
4. **Highlight a gotcha**: What's a common mistake?

技能位置:

位置 范围
~/.claude/skills/ 个人所有项目
.claude/skills/ 当前项目
Plugin skills 插件范围

调用技能:

/explain-code src/auth/login.ts

或让 Claude 自动调用(根据 description 匹配)。

Hooks(钩子)

Hooks 在特定事件时自动执行脚本。

配置示例:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write ."
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "if": "Bash(rm *)",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-rm.sh"
          }
        ]
      }
    ]
  }
}

可用 Hook 事件:

事件 触发时机
SessionStart 会话开始
UserPromptSubmit 用户提交提示
PreToolUse 工具执行前(可阻止)
PostToolUse 工具执行后
PermissionRequest 权限请求时
Stop Claude 完成响应
SessionEnd 会话结束

隐藏/高级技巧

快捷键和效率技巧

通用控制快捷键
快捷键 说明
Ctrl+C 取消当前输入或生成
Ctrl+D 退出 Claude Code
Ctrl+L 清除提示输入
Ctrl+R 搜索命令历史
Ctrl+B 后台运行任务
Ctrl+T 切换任务列表
Ctrl+O 切换记录查看器
Ctrl+GCtrl+X Ctrl+E 在默认编辑器中编辑
Shift+Tab 循环权限模式
Esc + Esc 回退或总结
文本编辑快捷键
快捷键 说明
Ctrl+K 删除到行尾
Ctrl+U 删除到行首
Ctrl+Y 粘贴删除的文本
Alt+B 向后移动一个词
Alt+F 向前移动一个词
模型切换快捷键
快捷键 说明
Option+P (macOS) / Alt+P (Win/Linux) 切换模型
Option+T (macOS) / Alt+T (Win/Linux) 切换扩展思考
Option+O (macOS) / Alt+O (Win/Linux) 切换快速模式
效率技巧

1. 使用 @ 提及文件

Analyze @src/auth/login.ts and suggest improvements

2. 使用 ! 直接运行命令

!npm test
Can you fix the failing tests?

3. 并行任务 - 使用 git worktree

# 创建工作树
git worktree add ../my-project-feature feature-branch

# 在另一个终端运行
cd ../my-project-feature
claude

4. 远程控制

claude remote-control

然后从 claude.ai/code 或 iOS/Android 应用连接。

5. 侧边问题 (/btw)

/btw What's the difference between useMemo and useCallback?

不添加到对话历史,快速获取答案。


调试和问题排查

诊断命令
# 运行诊断
claude doctor

# 会话内运行诊断
/doctor
调试模式
# 启用详细输出
claude --debug

# 或在会话中检查日志
cat ~/.claude/logs/claude-code-*.log
日志文件

日志位置:~/.claude/logs/

查看最近日志:

tail -100 ~/.claude/logs/claude-code-$(date +%Y-%m-%d).log
常见问题解决

1. 会话挂起

  • 使用 /clear 清除上下文
  • 使用 /compact 压缩对话
  • 使用 /doctor 检查环境

2. MCP 服务器连接失败

# 检查服务器状态
claude mcp list

# 重新添加服务器
claude mcp remove <server-name>
claude mcp add <server-name> --transport http <url>

3. 权限问题

# 检查当前权限模式
/permissions

# 重置权限设置
# 编辑 .claude/settings.json 或 ~/.claude/settings.json

4. 上下文过满

# 查看上下文使用情况
/context

# 压缩对话,指定保留重点
/compact focus on the API changes and modified files

最佳实践

CLAUDE.md 最佳实践

1. 保持简洁

  • 目标少于 200 行
  • 使用标题和列表组织
  • 具体且可验证的指令

示例对比:

# Good ✅
- Use 2-space indentation
- Run `npm test` before committing
- API handlers live in `src/api/handlers/`

# Bad ❌
- Format code properly
- Test your changes
- Keep files organized

2. 定期清理

  • 删除过时指令
  • 解决冲突规则
  • 只保留当前相关内容

3. 使用技能分解

当 CLAUDE.md 增长时,将多步骤流程移到技能中:

.claude/skills/
├── deploy/SKILL.md
├── code-review/SKILL.md
└── test/SKILL.md
上下文管理最佳实践

1. 主动压缩

/compact preserve the list of modified files

2. 使用 @imports 延迟加载

# CLAUDE.md
See @docs/api-patterns.md for API conventions.
See @docs/testing-guide.md for testing patterns.

只有在需要时才加载这些文件。

3. 避免上下文膨胀

  • 避免运行周期性轮询
  • 在上下文达到 50% 时手动压缩
  • 切换任务时使用 /clear
工作流最佳实践

1. 使用 Plan 模式进行架构决策

claude --permission-mode plan

适合:

  • 多文件更改
  • 不熟悉的代码库分析
  • 架构决策

2. 预授权常用操作

settings.json 中:

{
  "permissions": {
    "allow": [
      "Bash(npm run lint)",
      "Bash(npm test)",
      "Bash(git commit *)"
    ]
  }
}

3. 使用 Hooks 自动化

自动格式化代码:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write ."
          }
        ]
      }
    ]
  }
}

4. 安全考虑

  • 不要在 allow 规则中添加敏感文件
  • 使用 deny 阻止危险操作
  • 对于企业部署,使用 managed settings
  • 在 VM 或容器中运行 Claude Code

5. 子代理管理

# 查看运行的子代理
/tasks

# 终止后台代理
Ctrl+X Ctrl+K(按两次确认)

附录:CLAUDE.md 模板

# Project: [项目名称]

## 概述
简要描述项目功能和目标。

## 技术栈
- Framework: Next.js 14
- Language: TypeScript
- Database: PostgreSQL
- Testing: Jest

## 常用命令
- 开发: `npm run dev`
- 构建: `npm run build`
- 测试: `npm test`
- 代码检查: `npm run lint`

## 编码规范
- 使用 2 空格缩进
- 组件使用 PascalCase 命名
- 函数使用 camelCase 命名
- 所有新代码必须有测试

## 项目结构
- `src/components/` - React 组件
- `src/lib/` - 工具函数
- `src/api/` - API 路由
- `tests/` - 测试文件

## 工作流程
1. 创建功能分支
2. 编写代码和测试
3. 运行 `npm test` 确保测试通过
4. 提交 PR

## 注意事项
- 不要修改 `.env` 文件
- 不要直接提交到 main 分支
- PR 必须经过 code review

总结

Claude Code 是一个强大的终端 AI 编程助手。掌握以下要点,能让你的开发效率大幅提升:

层次 要点
入门 熟悉斜杠命令、@ 提及文件、! 运行命令
进阶 配置 CLAUDE.md、设置权限规则、使用 MCP 扩展
高级 创建 Skills、配置 Hooks、多 session 并行工作

推荐学习路径:

  1. 先熟悉基本命令和交互方式
  2. 学会创建和使用 CLAUDE.md
  3. 配置个人偏好(权限、常用命令预授权)
  4. 探索 MCP 服务器扩展能力
  5. 创建自己的 Skills 和 Hooks

祝你使用愉快!🚀

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐