<!-- title: Claude Code零基础入门：安装配置与首个项目全实战 -->

# Claude Code零基础入门：安装配置与首个项目全实战

## 概述

本教程面向从未使用过 Claude Code 的开发者，从零开始讲解安装、认证、项目配置和基本使用。学完后你将能够独立在终端中使用 Claude Code 完成代码编写、调试、Git 操作等日常开发任务。适合有基本终端操作经验的开发者。

## 前置条件

| 条件 | 说明 |
|------|------|
| **终端基础** | 能打开终端、执行基本命令（cd、ls 等） |
| **开发环境** | 至少有一个代码项目目录 |
| **Claude 账户** | Pro / Max / Team / Enterprise 订阅，或 Claude Console 账户 |
| **网络** | 稳定的互联网连接 |
| **操作系统** | macOS 13.0+ / Ubuntu 20.04+ / Debian 10+ / Windows 10 1809+ |
| **硬件** | 4GB+ RAM，x64 或 ARM64 处理器 |

> **没有订阅？** Claude Code 不支持免费计划。你需要订阅 Claude Pro（$20/月）或更高计划，也可以使用 Claude Console 按 API 用量付费。

---

## 第一步：理解 Claude Code 是什么

Claude Code 是 Anthropic 推出的**终端 AI 编程助手**。它不是普通的聊天机器人——它能：

- 🔍 **读取你的代码库**：自动理解项目结构、技术栈、代码逻辑
- ✏️ **编辑文件**：直接修改你的代码，修改前征求你的同意
- 🖥️ **执行命令**：运行测试、构建、部署等 Shell 命令
- 🔀 **操作 Git**：创建分支、提交代码、解决合并冲突
- 🔌 **连接外部服务**：通过 MCP 协议连接数据库、Issue 跟踪器等

与 ChatGPT 等 Web 端 AI 不同，Claude Code **运行在你的本地终端**，直接与你的代码和工具交互。

```mermaid
graph TB
    subgraph 你的开发环境
        A[终端 Terminal] --> B[Claude Code CLI]
        B --> C[代码文件]
        B --> D[Git 仓库]
        B --> E[Shell 命令]
        B --> F[测试框架]
    end
    subgraph Anthropic 云端
        G[Claude AI 模型]
    end
    B <-->|API 通信| G
    style B fill:#f9a825,stroke:#333,color:#000
    style G fill:#6366f1,stroke:#333,color:#fff
```

---

## 第二步：安装 Claude Code

### 2.1 macOS / Linux 安装（推荐方式）

打开终端，执行一行命令：

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

**预期输出：**

```
Downloading Claude Code...
Installing to ~/.claude/bin/
Claude Code installed successfully!
```

**原生安装的优势：**
- ✅ 自动后台更新，始终保持最新版本
- ✅ 无需手动管理 Node.js 版本
- ✅ 跨平台一致体验

### 2.2 Windows 安装

**PowerShell 方式（推荐）：**

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

**CMD 方式：**

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

> ⚠️ **注意区分 PowerShell 和 CMD：** PowerShell 提示符显示 `PS C:\`，CMD 显示 `C:\`。如果看到 `The token '&&' is not a valid statement separator` 错误，说明你在 PowerShell 中运行了 CMD 命令。

**建议安装 Git for Windows**（[下载地址](https://git-scm.com/downloads/win)），这样 Claude Code 可以使用 Bash 工具执行更丰富的命令。

### 2.3 Homebrew 安装（macOS 备选）

```bash
brew install --cask claude-code
```

Homebrew 提供两个版本：
- `claude-code`：稳定版，通常延迟约一周
- `claude-code@latest`：最新版，新功能立即可用

> ⚠️ Homebrew 安装**不会自动更新**，需要手动执行 `brew upgrade claude-code`。

### 2.4 WinGet 安装（Windows 备选）

```powershell
winget install Anthropic.ClaudeCode
```

手动更新：`winget upgrade Anthropic.ClaudeCode`

### 2.5 Linux 包管理器安装

```bash
# Debian/Ubuntu
curl -fsSL https://claude.ai/install.sh | bash

# 也可以使用 apt（如果官方仓库已配置）
sudo apt install claude-code

# Fedora/RHEL
sudo dnf install claude-code

# Alpine
sudo apk add claude-code
```

> **Alpine 特别注意：** 需要先安装依赖 `apk add libgcc libstdc++ ripgrep`，并在 `settings.json` 中设置 `"USE_BUILTIN_RIPGREP": "0"`。

### 2.6 验证安装

```bash
claude --version
```

**预期输出：**

```
Claude Code v1.0.x
```

更详细的健康检查：

```bash
claude doctor
```

这个命令会检查安装完整性、认证状态、网络连通性等。

### 常见安装问题排查

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| `command not found` | PATH 未配置 | 重启终端，或手动添加 `~/.claude/bin` 到 PATH |
| `Permission denied` | 权限不足 | macOS/Linux：`chmod +x ~/.claude/bin/claude` |
| 网络超时 | 防火墙/代理 | 检查网络配置，参见 [网络配置文档](https://code.claude.com/docs/en/network-config) |
| PowerShell 报错 | CMD/PS 混淆 | 确认当前 Shell 类型，使用对应安装命令 |

---

## 第三步：登录认证

### 3.1 首次登录

安装完成后，直接运行：

```bash
claude
```

系统会自动弹出浏览器，引导你完成 Anthropic 账户认证。

**支持的账户类型：**

| 账户类型 | 说明 | 适用场景 |
|----------|------|----------|
| Claude Pro | $20/月订阅 | 个人开发者 |
| Claude Max | 更高额度订阅 | 重度使用者 |
| Claude Team/Enterprise | 团队计划 | 企业团队 |
| Claude Console | API 预付费 | 按量计费用户 |
| Amazon Bedrock | AWS 云服务 | 企业 AWS 用户 |
| Google Vertex AI | GCP 云服务 | 企业 GCP 用户 |

### 3.2 切换账户

在已运行的会话中输入：

```
/login
```

即可重新选择账户类型或切换登录。

### 3.3 API Key 方式（Console 用户）

如果你使用 Claude Console，可以设置环境变量：

```bash
export ANTHROPIC_API_KEY="sk-ant-xxxxx"
```

登录成功后，凭证会保存在本地，后续使用无需重复登录。

---

## 第四步：启动第一个会话

### 4.1 进入项目目录

```bash
cd /path/to/your/project
claude
```

**预期看到：**

```
╭─────────────────────────────────────────╮
│  Claude Code v1.0.x                     │
│  Model: claude-sonnet-4-6               │
│  Working: /path/to/your/project         │
╰─────────────────────────────────────────╯
>
```

你会看到版本号、当前使用的模型、以及工作目录。

### 4.2 交互式操作基础

Claude Code 的交互非常直观——就像跟一个同事对话：

```mermaid
flowchart LR
    A[输入自然语言指令] --> B[Claude 理解分析]
    B --> C{需要执行操作?}
    C -->|读取文件| D[自动读取相关文件]
    C -->|修改代码| E[展示修改方案]
    C -->|执行命令| F[请求权限执行]
    D --> G[返回分析结果]
    E --> H[等待你的批准]
    F --> I[等待你的批准]
    H --> J[应用修改]
    I --> K[执行命令]
    style A fill:#e3f2fd
    style J fill:#c8e6c9
    style K fill:#c8e6c9
```

---

## 第五步：提出你的第一个问题

先让 Claude 理解你的项目。试试这些命令：

```
> what does this project do?
```

Claude 会分析你的文件结构，给出项目概述。你可以继续追问：

```
> what technologies does this project use?
```

```
> where is the main entry point?
```

```
> explain the folder structure
```

**💡 实用技巧：** Claude Code 自动读取项目文件作为上下文，你不需要手动粘贴代码。它会在需要时自动查找和阅读相关文件。

---

## 第六步：第一次代码修改

现在让 Claude 帮你写代码。从一个简单任务开始：

```
> add a hello world function to the main file
```

**Claude 的执行流程：**

1. **查找文件**：定位项目的主入口文件
2. **展示方案**：显示具体要修改的内容（类似 git diff）
3. **请求批准**：等待你确认
4. **执行修改**：写入文件

你会看到类似这样的提示：

```
Edit: src/index.js
+ function helloWorld() {
+   console.log("Hello, World!");
+ }
+ 
+ helloWorld();

Allow this edit? (y/n/a/e)
```

| 按键 | 含义 |
|------|------|
| `y` | 允许本次修改 |
| `n` | 拒绝修改 |
| `a` | 本次会话全部允许（Accept all） |
| `e` | 在编辑器中打开查看 |

---

## 第七步：Git 操作实战

Claude Code 可以用自然语言操作 Git：

### 查看变更

```
> what files have I changed?
```

### 提交代码

```
> commit my changes with a descriptive message
```

Claude 会自动分析变更内容，生成语义化的提交信息。

### 分支管理

```
> create a new branch called feature/user-auth
```

### 查看历史

```
> show me the last 5 commits
```

### 解决冲突

```
> help me resolve merge conflicts
```

---

## 第八步：修复 Bug 和添加功能

### 修复 Bug

描述你遇到的问题，Claude 会定位并修复：

```
> there's a bug where users can submit empty forms - fix it
```

Claude 的处理过程：
1. 搜索相关代码文件
2. 分析表单验证逻辑
3. 定位缺陷
4. 实现修复
5. 如果有测试，自动运行验证

### 添加功能

用自然语言描述你想要的功能：

```
> add input validation to the user registration form
```

或者分步骤描述：

```
> I need to add email verification:
> 1. add a verified field to the User model
> 2. send a verification email on registration
> 3. add an endpoint to handle verification links
> 4. update the login flow to check verification status
```

---

## 实战案例：从零创建一个 Todo API

让我们用一个完整案例串联所有知识。假设你要创建一个 Node.js + Express 的 Todo API。

### 步骤 1：初始化项目

```bash
mkdir todo-api && cd todo-api
npm init -y
npm install express
claude
```

### 步骤 2：让 Claude 创建基础结构

```
> create a basic Express.js REST API for todos with CRUD operations.
> Use ES modules syntax. Store todos in memory for now.
> Include proper error handling.
```

Claude 会创建类似这样的文件结构：

```
todo-api/
├── package.json
├── src/
│   ├── index.js        # 入口文件
│   ├── routes/
│   │   └── todos.js    # Todo 路由
│   └── middleware/
│       └── errorHandler.js  # 错误处理
└── CLAUDE.md           # Claude 配置
```

### 步骤 3：添加测试

```
> add unit tests for all todo endpoints using vitest
> run the tests and fix any failures
```

### 步骤 4：完善功能

```
> add input validation: title is required and max 200 chars
> add pagination to the GET /todos endpoint
> add a health check endpoint at GET /health
```

### 步骤 5：Git 提交

```
> commit all changes with a descriptive message
```

Claude 会生成类似：

```
feat: implement Todo API with CRUD operations

- Add Express.js REST API with in-memory storage
- Implement POST/GET/PUT/DELETE /todos endpoints
- Add input validation and error handling
- Add unit tests with vitest
- Add pagination support and health check
```

---

## 配置你的环境：CLAUDE.md 文件

CLAUDE.md 是 Claude Code 的核心配置文件。它告诉 Claude 你的项目规则、代码风格和工作流偏好。

### 快速生成

在项目根目录运行：

```
> /init
```

Claude 会分析你的代码库，自动生成一个基础 CLAUDE.md。

### 手动编写示例

```markdown
# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')
- Use TypeScript strict mode

# Workflow
- Be sure to typecheck when you're done making code changes
- Prefer running single tests, not the whole test suite
- Run `npm run lint` before committing

# Testing
- Use vitest for unit tests
- Always test edge cases
- Avoid mocks when possible

# Git
- Branch naming: feature/description, fix/description
- Commit messages: conventional commits format
```

### CLAUDE.md 文件位置与作用域

```mermaid
graph TD
    A["~/.claude/CLAUDE.md<br/>全局：所有项目生效"] --> B["./CLAUDE.md<br/>项目级：当前项目共享"]
    B --> C["./CLAUDE.local.md<br/>个人项目配置（不提交 Git）"]
    B --> D["子目录/CLAUDE.md<br/>按需加载"]

    style A fill:#fff3e0,stroke:#333
    style B fill:#e8f5e9,stroke:#333
    style C fill:#fce4ec,stroke:#333
    style D fill:#e3f2fd,stroke:#333
```

| 位置 | 作用 | Git |
|------|------|-----|
| `~/.claude/CLAUDE.md` | 所有项目生效 | 不提交 |
| `./CLAUDE.md` | 项目级，团队共享 | ✅ 提交 |
| `./CLAUDE.local.md` | 个人项目偏好 | 加入 .gitignore |
| 子目录 `CLAUDE.md` | 访问该目录时按需加载 | ✅ 提交 |

**关键原则：保持 CLAUDE.md 简洁。** 每一行都问自己："删掉这行会导致 Claude 犯错吗？" 如果不会，就删掉。过长的 CLAUDE.md 反而会让 Claude 忽略你的真实指令。

---

## 必备命令速查表

| 命令 | 用途 | 示例 |
|------|------|------|
| `claude` | 启动交互模式 | `claude` |
| `claude "task"` | 执行一次性任务 | `claude "fix the build error"` |
| `claude -p "query"` | 单次查询后退出 | `claude -p "explain this function"` |
| `claude -c` | 继续最近的对话 | `claude -c` |
| `claude -r` | 恢复之前的会话 | `claude -r` |
| `/clear` | 清空对话历史 | `/clear` |
| `/help` | 显示帮助 | `/help` |
| `/login` | 切换账户 | `/login` |
| `/init` | 生成 CLAUDE.md | `/init` |
| `/config` | 打开配置 | `/config` |
| `exit` 或 `Ctrl+D` | 退出 Claude Code | `exit` |
| `Shift+Tab` | 切换权限模式 | — |
| `Tab` | 命令补全 | — |
| `↑` | 历史命令 | — |

---

## 初学者进阶建议

### 1. 先探索，再编码

不要一上来就让 Claude 写代码。先用 Plan 模式理解代码：

```
> analyze the database schema
```

```
> explain how authentication works in this project
```

理解清楚后再让 Claude 实施修改。按 `Shift+Tab` 可以切换到 Plan 模式。

### 2. 提供具体的上下文

| ❌ 模糊的提示 | ✅ 具体的提示 |
|-------------|-------------|
| "fix the bug" | "fix the login bug where users see a blank screen after entering wrong credentials" |
| "add tests" | "write unit tests for the email validation function in utils.js, cover edge cases" |
| "make it better" | "refactor the auth module to use async/await instead of callbacks" |

### 3. 使用 `@` 引用文件

用 `@` 符号直接引用文件，比描述文件路径更高效：

```
> review @src/auth/login.js for security issues
```

```
> refactor @src/utils/helpers.js to use modern ES syntax
```

### 4. 管理上下文窗口

Claude 的上下文窗口有限。在长会话中注意：

- 使用 `/compact` 命令压缩对话历史
- 用 `/clear` 开始新的对话
- 复杂任务分成多个小会话

### 5. 给 Claude 验证手段

让 Claude 能自己验证工作成果：

```
> implement the validateEmail function.
> test cases: user@example.com → true, "invalid" → false, user@.com → false
> run the tests after implementing
```

这样 Claude 会自己运行测试、检查结果、迭代修复，直到全部通过。

---

## 工作流程全景图

```text
flowchart TB
    subgraph 安装阶段
        A1[选择安装方式] --> A2[执行安装命令]
        A2 --> A3[验证: claude --version]
        A3 --> A4[运行 claude doctor]
    end

    subgraph 认证阶段
        B1[运行 claude] --> B2[浏览器登录]
        B2 --> B3[认证成功]
    end

    subgraph 项目配置
        C1[cd 进入项目] --> C2[/init 生成 CLAUDE.md]
        C2 --> C3[编辑完善规则]
    end

    subgraph 日常使用
        D1[启动会话] --> D2[探索理解代码]
        D2 --> D3[描述需求]
        D3 --> D4[审核 Claude 的方案]
        D4 --> D5[批准执行]
        D5 --> D6[验证结果]
        D6 --> D7{满意?}
        D7 -->|否| D3
        D7 -->|是| D8[Git 提交]
    end

    A4 --> B1
    B3 --> C1
    C3 --> D1

    style A1 fill:#e3f2fd,stroke:#333
    style B1 fill:#fff3e0,stroke:#333
    style C1 fill:#e8f5e9,stroke:#333
    style D1 fill:#fce4ec,stroke:#333
```

---

## 平台选择指南

Claude Code 不只有终端 CLI。根据场景选择最适合的界面：

| 界面 | 适合场景 | 地址 |
|------|----------|------|
| **终端 CLI** | 日常开发、深度编码 | `claude` 命令 |
| **桌面应用** | 不习惯终端的用户 | [下载](https://claude.ai/download) |
| **VS Code 扩展** | IDE 内集成 | 扩展市场搜索 Claude Code |
| **JetBrains 插件** | IntelliJ/WebStorm 等 | 插件市场搜索 Claude Code |
| **Web 版** | 浏览器内使用 | [claude.ai/code](https://claude.ai/code) |
| **Slack 集成** | 团队协作 | Slack App 目录 |

---

## 延伸阅读

- [Claude Code 官方文档](https://code.claude.com/docs/en/overview) — 完整的功能参考和 API 文档
- [Claude Code 最佳实践](https://code.claude.com/docs/en/best-practices) — 从 Anthropic 内部团队总结的高效使用模式
- [Claude Code 常见工作流](https://code.claude.com/docs/en/common-workflows) — 详细的场景化操作指南
- [Claude Code CLI 完整参考](https://code.claude.com/docs/en/cli-reference) — 所有命令行参数和选项
- [Claude Code 中文上手指南](https://github.com/lhfer/claude-howto-zh-cn) — 社区维护的中文全面指南

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适合训练营类型** | AI 工具入门营、前端/后端开发训练营、DevOps 培训 |
| **教学时长** | 约 2-3 小时（含实操） |
| **学员基础要求** | 能使用终端、有基本编程经验 |
| **实操占比** | 70% 实操 + 30% 讲解 |
| **建议分组** | 2-3 人一组，每组一个实际项目 |
| **考核方式** | 学员独立完成安装→配置→首次代码修改→Git 提交全流程 |

---

## 参考来源

1. [Quickstart - Claude Code Docs](https://code.claude.com/docs/en/quickstart) — Anthropic 官方快速入门指南，涵盖安装、登录、首次会话的完整步骤
2. [Advanced Setup - Claude Code Docs](https://code.claude.com/docs/en/setup) — 官方高级安装配置文档，包含系统要求、平台特定安装和版本管理
3. [Best Practices for Claude Code](https://code.claude.com/docs/en/best-practices) — 官方最佳实践指南，包含 CLAUDE.md 配置、上下文管理、权限设置等
4. [Claude Code: The Complete Setup Guide for macOS, Windows, and Linux](https://dev.to/devdaily_2026/claude-code-the-complete-setup-guide-for-macos-windows-and-linux-3dbl) — DEV 社区全平台安装详解
5. [Claude Code 中文全面上手指南](https://github.com/lhfer/claude-howto-zh-cn) — GitHub 社区维护的中文完整教程，覆盖从基础到高级用法

> [!tip] 51学通信知识星球
> **星主：爱卫生**（微信：gprshome201101）——公众号「51学通信」创办者，19 年通信行业运维与讲师经验，著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书（各大电商平台有售）。
> **星球定位**：深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域，主打运维岗位与信令分析。
> **当前规模**：5200 篇主题 / 990 个回答，198 元/年。
> **加入福利**：加入星球后请加爱卫生微信，拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题，另有群内分享。
> **AI 加持**：51学通信知识星球已作为 skill 接入 WorkBuddy，使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例，做总结、找文档和 PPT 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
