第 39 章

Claude Code 安装与核心工作流:CLI / Desktop / VS Code / JetBrains 全平台

第三十九章:Claude Code 安装与配置:CLI、IDE 插件与快捷键体系

39.1 Claude Code 是什么

Claude Code 是 Anthropic 官方发布的命令行 AI 编程助手。与 Claude.ai 网页界面不同,Claude Code 直接在你的终端运行,能够读写本地文件、执行 bash 命令、管理 git 仓库——本质上它是一个可以真正操作你代码库的 AI Agent。

Claude Code 的核心特性:

Claude Code 与 Cursor/GitHub Copilot 的关键区别在于:它是 Agent 而非代码补全工具。Claude Code 不只是在你打字时补全代码——它能理解你的意图、制定计划、自主执行多步操作。

39.2 安装 Claude Code

39.2.1 系统要求

项目 要求
操作系统 macOS 10.15+, Linux (Ubuntu 20.04+, Debian 10+), Windows 10/11 (WSL2)
Node.js 18.0 及以上
内存 建议 8GB+
磁盘 至少 500MB 可用空间
网络 需要访问 Anthropic API(api.anthropic.com

39.2.2 安装步骤

方法一:npm 全局安装(推荐)

# 确认 Node.js 版本
node --version  # 需要 >= 18.0.0

# 全局安装 Claude Code
npm install -g @anthropic-ai/claude-code

# 验证安装
claude --version
# 输出类似:Claude Code 1.x.x

方法二:使用 npx 临时运行(无需全局安装)

npx @anthropic-ai/claude-code

Windows 用户(WSL2)

# 在 Windows Terminal 中打开 WSL2
wsl

# 然后在 WSL2 中执行安装命令
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
npm install -g @anthropic-ai/claude-code

39.2.3 更新 Claude Code

# 更新到最新版本
npm update -g @anthropic-ai/claude-code

# 或者重新安装
npm install -g @anthropic-ai/claude-code@latest

39.3 API 密钥配置

39.3.1 获取 API 密钥

  1. 访问 https://console.anthropic.com
  2. 登录或创建账户
  3. 进入「API Keys」页面
  4. 点击「Create Key」,选择适当的权限范围
  5. 复制生成的 API 密钥(以 sk-ant- 开头)

注意:Claude Code 需要 API 调用权限,确保账户有足够的额度。Claude Code 使用 claude-sonnet-4-5claude-opus-4-5 模型,消耗 API token。

39.3.2 配置 API 密钥

方式一:环境变量(推荐)

# 在 ~/.bashrc 或 ~/.zshrc 中添加
export ANTHROPIC_API_KEY="sk-ant-api03-xxxxxxxxxxxx"

# 使配置立即生效
source ~/.zshrc

方式二:首次运行时配置

claude
# 如果未设置 API Key,会自动提示输入
# > Enter your Anthropic API key:

方式三:项目级 .env 文件

# 在项目根目录创建 .env 文件
echo "ANTHROPIC_API_KEY=sk-ant-api03-xxxxxxxxxxxx" >> .env

# 重要:将 .env 添加到 .gitignore
echo ".env" >> .gitignore

39.3.3 使用 Claude Code 连接 claude.ai 账户(非 API)

如果你有 Claude.ai Pro 订阅但没有 API 账户,可以通过 OAuth 连接:

claude login
# 会打开浏览器,引导完成 claude.ai 登录
# 登录后 Claude Code 使用你的 Pro 账户权限

39.4 全局配置文件

Claude Code 的全局配置存储在 ~/.claude.json

{
  "apiKeyHelper": "",
  "model": "claude-opus-4-5",
  "smallFastModel": "claude-haiku-4-5",
  "theme": "dark",
  "preferredNotifChannel": "terminal-bell",
  "verbose": false,
  "maxFileSize": 10485760,
  "ignorePatterns": [
    "node_modules",
    ".git",
    "dist",
    "build",
    "*.min.js",
    "*.lock"
  ]
}

配置字段说明

字段 说明 默认值
model 主要使用的模型 claude-sonnet-4-5
smallFastModel 简单任务使用的轻量模型 claude-haiku-4-5
theme 终端颜色主题(dark/light/auto) auto
verbose 显示详细日志 false
maxFileSize 单文件最大读取大小(字节) 10MB
ignorePatterns 全局忽略的文件/目录模式 见上

通过 CLI 修改全局配置:

# 设置默认模型
claude config set model claude-opus-4-5

# 查看所有配置
claude config list

# 查看特定配置项
claude config get model

39.5 项目级配置:CLAUDE.md

CLAUDE.md 是 Claude Code 最重要的项目级配置文件,位于项目根目录。当 Claude Code 在项目目录中启动时,会自动读取并遵守 CLAUDE.md 中的所有指令。

39.5.1 CLAUDE.md 的作用

  1. 告知项目背景:架构、技术栈、特殊约定
  2. 定义代码规范:命名规范、文件组织方式、禁止的模式
  3. 声明 MCP 工具:可用的 MCP Server 和使用原则
  4. 指定 bash 命令:项目的测试、构建、运行命令
  5. 描述工作流:开发流程、提交规范、发布流程

39.5.2 完整 CLAUDE.md 示例

# 项目:TechBlog Platform

## 技术栈
- 后端:Python 3.11, FastAPI, PostgreSQL 15, Redis
- 前端:React 18, TypeScript, Tailwind CSS v3
- 基础设施:Docker Compose(开发),Kubernetes(生产)
- 测试:pytest(后端),Vitest(前端)

## 常用命令

### 开发环境
\`\`\`bash
# 启动完整开发环境
docker compose up -d

# 仅启动数据库
docker compose up -d postgres redis

# 运行后端(开发模式)
cd backend && uvicorn app.main:app --reload --port 8000

# 运行前端
cd frontend && npm run dev
\`\`\`

### 测试
\`\`\`bash
# 后端单元测试
cd backend && pytest tests/ -v

# 后端测试(含覆盖率)
cd backend && pytest tests/ --cov=app --cov-report=html

# 前端测试
cd frontend && npm run test

# E2E 测试
npm run test:e2e
\`\`\`

### 数据库
\`\`\`bash
# 生成数据库迁移
cd backend && alembic revision --autogenerate -m "描述"

# 执行迁移
cd backend && alembic upgrade head

# 回滚迁移
cd backend && alembic downgrade -1
\`\`\`

## 代码规范

### Python
- 使用 Black 格式化,行长度 100
- 使用 isort 排序导入
- 所有函数需要类型注解
- 使用 pydantic v2 模型,不使用 dict
- 异步函数优先(async/await)

### TypeScript
- strict 模式开启,不使用 any
- 组件使用函数式(不用 class)
- 状态管理使用 Zustand,不用 Redux
- API 调用统一通过 src/api/ 目录

### Git 提交
格式:`<type>(<scope>): <description>`
- type: feat/fix/docs/style/refactor/test/chore
- scope: backend/frontend/infra/deps
- 示例:`feat(backend): add user authentication endpoint`

## 项目结构

\`\`\`
techblog/
├── backend/
│   ├── app/
│   │   ├── api/           # API 路由(按资源分文件)
│   │   ├── core/          # 配置、数据库连接、安全
│   │   ├── models/        # SQLAlchemy 模型
│   │   ├── schemas/       # Pydantic schemas
│   │   └── services/      # 业务逻辑层
│   └── tests/
├── frontend/
│   ├── src/
│   │   ├── api/           # API 客户端函数
│   │   ├── components/    # React 组件
│   │   ├── pages/         # 页面组件
│   │   ├── stores/        # Zustand stores
│   │   └── types/         # TypeScript 类型定义
│   └── tests/
└── infra/
    ├── docker/
    └── k8s/
\`\`\`

## 重要约定

1. **永不直接操作 main 分支**,所有更改通过 PR
2. **测试先行**:新功能先写测试,再实现
3. **敏感信息**:所有 Secret 和 API Key 通过环境变量,永不提交代码
4. **数据库迁移**:修改 Model 后必须生成迁移文件
5. **错误处理**:所有 API 端点必须有明确的错误响应 schema

## MCP 工具(如已配置)
- 使用 filesystem MCP 读写本地文件
- 使用 postgres MCP 查询数据库(只读)
- 数据库写操作必须通过代码,不能通过 MCP 直接操作

39.5.3 CLAUDE.md 的层级继承

CLAUDE.md 支持层级继承——子目录中的 CLAUDE.md 会继承父目录的配置,并可以覆盖特定设置:

project/
├── CLAUDE.md          # 项目全局配置
├── backend/
│   └── CLAUDE.md      # 后端专属配置(继承父级,覆盖 Python 相关设置)
└── frontend/
    └── CLAUDE.md      # 前端专属配置(继承父级,覆盖 TypeScript 相关设置)

39.6 斜杠命令系统

Claude Code 提供了丰富的斜杠命令(Slash Commands),这些命令在会话中直接输入,以 / 开头。

39.6.1 核心斜杠命令

通用命令

/help           显示所有可用命令的帮助信息
/clear          清除当前会话的上下文历史
/exit 或 /quit  退出 Claude Code
/verbose        切换详细日志模式
/model          显示或切换使用的模型

版本控制命令

/commit         分析未暂存的更改,生成 commit message 并提交
                示例:/commit
                Claude 会:
                - 运行 git diff 查看更改
                - 生成符合约定的 commit message
                - 询问确认后执行 git commit

/pr             创建 Pull Request
                示例:/pr "修复登录页面的内存泄漏"
                Claude 会:
                - 分析当前分支与 main 的差异
                - 生成 PR 标题和描述
                - 通过 gh CLI 或 API 创建 PR

/review-pr      审查 Pull Request
                示例:/review-pr 123
                Claude 会:
                - 获取 PR #123 的所有更改
                - 检查代码质量、潜在 bug、安全问题
                - 生成详细的审查意见

项目命令

/init           在当前目录初始化 Claude Code 项目(生成 CLAUDE.md 模板)
/status         显示项目状态(git status, 待处理任务等)
/summarize      生成当前项目或文件的摘要

调试命令

/doctor         检查 Claude Code 的配置和环境
/cost           显示当前会话的 token 使用量和估算费用
/terminal-setup 配置终端集成(macOS iTerm2, Ghostty 等)

39.6.2 /commit 命令详解

# 基础用法
/commit

# Claude Code 的执行流程:
# 1. 运行 git status 查看更改的文件
# 2. 运行 git diff --staged 查看已暂存的更改
# 3. 运行 git diff 查看未暂存的更改
# 4. 分析 CLAUDE.md 中的 commit 规范
# 5. 生成符合规范的 commit message
# 6. 显示给用户确认
# 7. 确认后执行 git add -A && git commit -m "..."

示例输出:

$ /commit

Analyzing changes...

Files changed:
  M  src/api/auth.py
  M  tests/test_auth.py
  A  docs/authentication.md

Proposed commit message:
  feat(backend): implement JWT refresh token rotation

  - Add RefreshToken model with device tracking
  - Implement token rotation on each refresh
  - Add cleanup job for expired tokens
  - Update authentication docs

Confirm? [Y/n]

39.6.3 /review-pr 命令详解

# 审查特定 PR(数字 ID)
/review-pr 123

# 审查当前分支对应的 PR
/review-pr

# 审查并生成结构化报告
/review-pr 123 --format report

审查内容默认包括

39.7 IDE 插件集成

39.7.1 VS Code 集成

安装 Claude Code VS Code 插件

  1. 打开 VS Code
  2. 进入扩展市场(Ctrl+Shift+X / Cmd+Shift+X)
  3. 搜索「Claude Code」
  4. 安装 Anthropic 官方插件

插件功能

VS Code 配置settings.json):

{
  "claude-code.apiKey": "",
  "claude-code.model": "claude-sonnet-4-5",
  "claude-code.enableInlineSuggestions": true,
  "claude-code.enableCodeLens": true,
  "claude-code.contextLines": 50,
  "claude-code.theme": "auto",
  "claude-code.keybindings.openPanel": "ctrl+shift+a",
  "claude-code.keybindings.explain": "ctrl+shift+e",
  "claude-code.keybindings.fix": "ctrl+shift+f"
}

39.7.2 JetBrains 系列插件

支持 IntelliJ IDEA、PyCharm、WebStorm、GoLand 等:

  1. 进入 File → Settings → Plugins(macOS:Preferences → Plugins
  2. 搜索「Claude Code」
  3. 安装官方插件并重启 IDE

插件快捷键(JetBrains)

快捷键 功能
Alt+Shift+C 打开 Claude Code 面板
Alt+Shift+E 解释选中的代码
Alt+Shift+F 修复选中代码中的问题
Alt+Shift+T 为选中代码生成测试
Alt+Shift+D 为选中代码生成文档

39.8 快捷键体系

39.8.1 终端内快捷键

在终端中运行 Claude Code 时,以下快捷键在 REPL 模式下可用:

快捷键 功能
Ctrl+C 中断当前 AI 响应
Ctrl+D 退出 Claude Code
Ctrl+L 清屏(不清除上下文)
/ 浏览历史命令
Tab 自动补全命令和斜杠命令
Ctrl+R 搜索历史命令
Esc 取消当前输入

39.8.2 VS Code 快捷键

安装 VS Code 插件后的默认快捷键:

快捷键 功能
Ctrl+Shift+A (Win/Linux) / Cmd+Shift+A (Mac) 打开/关闭 Claude Code 侧边栏
Ctrl+Shift+E / Cmd+Shift+E 解释选中代码
Ctrl+Shift+F / Cmd+Shift+F 修复选中代码
Ctrl+Shift+T / Cmd+Shift+T 为选中代码生成测试
Ctrl+Shift+D / Cmd+Shift+D 生成文档注释
Ctrl+Shift+/ / Cmd+Shift+/ 在当前上下文中提问

自定义快捷键(keybindings.json):

[
  {
    "key": "ctrl+alt+c",
    "command": "claude-code.openPanel",
    "when": "editorFocus"
  },
  {
    "key": "ctrl+alt+r",
    "command": "claude-code.reviewFile",
    "when": "editorFocus"
  },
  {
    "key": "ctrl+alt+t",
    "command": "claude-code.generateTests",
    "when": "editorTextFocus && editorHasSelection"
  }
]

39.9 Hooks 配置

Hooks 是 Claude Code 的高级功能,允许你在特定事件发生时自动执行自定义脚本。这些 hooks 由 Claude Code 进程本身执行,而非 AI 模型。

39.9.1 配置 Hooks

Hooks 在 ~/.claude/settings.json(全局)或项目的 .claude/settings.json 中配置:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo '即将执行 bash 命令:' && cat"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          {
            "type": "command",
            "command": "npx prettier --write \"$TOOL_ARG_PATH\" 2>/dev/null || true"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "notify-send 'Claude Code' 'Task completed!' 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

39.9.2 Hook 事件类型

事件 触发时机
PreToolUse 工具调用前(可以阻止执行)
PostToolUse 工具调用后
Notification Claude Code 发送通知时
Stop AI 完成任务时
SubagentStop 子 Agent 完成时

39.9.3 实用 Hook 示例

自动格式化写入的代码

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [{
          "type": "command",
          "command": "npx prettier --write \"$TOOL_ARG_PATH\" 2>/dev/null || true"
        }]
      }
    ]
  }
}

命令执行前的安全确认

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "if echo \"$TOOL_ARG_COMMAND\" | grep -q 'rm\\|delete\\|drop'; then echo 'DANGEROUS: Please review'; fi"
        }]
      }
    ]
  }
}

任务完成桌面通知(macOS)

{
  "hooks": {
    "Stop": [{
      "hooks": [{
        "type": "command",
        "command": "osascript -e 'display notification \"任务已完成\" with title \"Claude Code\"'"
      }]
    }]
  }
}

39.10 网络代理配置

在企业环境或需要通过代理访问网络时:

# 设置 HTTP 代理
export HTTPS_PROXY=http://proxy.company.com:8080
export HTTP_PROXY=http://proxy.company.com:8080
export NO_PROXY=localhost,127.0.0.1,.internal.company.com

# 或在 .claude.json 中配置
{
  "proxy": "http://proxy.company.com:8080"
}

小结

本章全面介绍了 Claude Code 的安装、配置体系和各类集成选项。从 npm 安装到 API 密钥配置,从 CLAUDE.md 项目配置到 Hooks 自动化,Claude Code 提供了深度可定制的开发工作流。

关键要点:

  1. CLAUDE.md 是项目配置的核心,告诉 Claude Code 项目背景、规范和工作流
  2. 斜杠命令(/commit、/review-pr 等)大幅简化 Git 工作流
  3. VS Code 和 JetBrains 插件提供 IDE 原生集成体验
  4. Hooks 机制允许在工具调用前后自动执行自定义操作
  5. 全局配置(~/.claude.json)和项目配置(.claude/settings.json)分层管理

下一章将深入 Claude Code 的核心工作流:文件编辑、bash 执行与项目导航的实战技巧。

本章评分
4.8  / 5  (3 评分)

💬 留言讨论