Skip to main content

第一次使用Claude Code

完成了安装和认证,今天开始第一次实战体验。带你从零开始完成第一个编程任务。

启动Claude Code

基本启动

打开终端,输入:

claude

首次启动时,你会看到欢迎信息:

╔════════════════════════════════════════════╗
║ ║
║ Welcome to Claude Code (Beta) ║
║ ║
║ Your AI-powered coding assistant ║
║ ║
╚════════════════════════════════════════════╝

Connected to: claude-3-7-sonnet-20250219
Working directory: /Users/username/project

How can I help you code today?

在特定项目中启动

想在特定项目中使用Claude Code:

# 切换到项目目录
cd ~/my-project

# 启动Claude Code
claude

Claude Code会自动识别当前目录作为工作目录。

启动选项

# 指定工作目录
claude --directory /path/to/project

# 指定模型
claude --model claude-3-opus

# 显示详细日志
claude --verbose

# 查看所有选项
claude --help

第一个任务:修改文件

从简单的任务开始:创建并修改一个Python脚本。

步骤1:创建文件

在Claude Code中输入:

请创建一个名为hello.py的文件,内容是打印"Hello, Claude Code!"

Claude Code会:

  1. 理解你的意图
  2. 创建文件
  3. 写入代码
  4. 显示结果

你会看到类似的输出:

I'll create a hello.py file for you.

📝 Creating: hello.py

✓ File created successfully

Content:
───────────────────────────────
print("Hello, Claude Code!")
───────────────────────────────

The file has been created in your current directory.

步骤2:验证文件

在另一个终端窗口(或暂时退出Claude Code),验证文件:

# 查看文件内容
cat hello.py

# 运行文件
python hello.py
# 输出: Hello, Claude Code!

步骤3:修改文件

回到Claude Code,输入:

请修改hello.py,添加一个函数来接收用户名并打印问候语

Claude Code会自动修改文件:

def greet(name):
"""打印个性化的问候语"""
print(f"Hello, {name}! Welcome to Claude Code!")

if __name__ == "__main__":
import sys

if len(sys.argv) > 1:
name = sys.argv[1]
else:
name = "Friend"

greet(name)

第二个任务:理解现有代码

现在学习如何让Claude Code理解和分析现有代码。

步骤1:请求代码分析

请分析hello.py的代码结构并解释它的工作原理

Claude Code会给出详细分析:

Let me analyze the hello.py file:

📊 Code Structure Analysis

1. Function Definition
- greet(name): 接收一个name参数并打印问候语
- Uses f-string for formatting
- Includes docstring for documentation

2. Main Block
- Uses if __name__ == "__main__" pattern
- Imports sys module for command-line arguments
- Handles two scenarios:
a) User provides name as argument
b) No argument provided (defaults to "Friend")

3. How it works:
✓ User runs: python hello.py Alice
✓ sys.argv[1] captures "Alice"
✓ greet("Alice") is called
✓ Output: "Hello, Alice! Welcome to Claude Code!"

4. Best Practices Used:
✓ Function with clear purpose
✓ Docstring documentation
✓ Default value handling
✓ Main block guard

步骤2:请求改进建议

这段代码有什么可以改进的地方吗?

Claude Code会提供专业建议并可以直接实现改进。

第三个任务:调试错误

学习如何使用Claude Code修复bug。

步骤1:创建有bug的代码

创建一个calculator.py文件,包含加减乘除四个函数

步骤2:引入一个错误

手动编辑文件,在除法函数中引入除零错误:

def divide(a, b):
return a / b # 没有检查b是否为0

步骤3:请求Claude Code修复

在Claude Code中:

calculator.py的divide函数有问题,请帮我修复并添加错误处理

Claude Code会:

  1. 识别问题
  2. 提供修复方案
  3. 实现改进
def divide(a, b):
"""
除法运算,包含除零错误处理

Args:
a: 被除数
b: 除数

Returns:
除法结果

Raises:
ValueError: 当除数为0时
"""
if b == 0:
raise ValueError("除数不能为零")
return a / b

理解Claude Code的工作流程

1. 对话式交互

Claude Code通过自然语言对话理解你的意图:

你: 创建一个Express服务器,监听3000端口

Claude: I'll create an Express server for you.
[创建server.js文件并实现代码]

你: 添加一个GET /api/hello路由

Claude: I'll add that route to your server.
[修改server.js,添加路由]

2. 上下文理解

Claude Code会记住对话历史:

你: 创建一个User类,包含name和email属性

Claude: [创建User类]

你: 添加一个验证email格式的方法

Claude: I'll add an email validation method to the User class.
[自动找到User类并添加方法]

3. 自主探索

当你提出复杂需求时,Claude Code会:

  • 自动探索项目结构
  • 找到相关文件
  • 理解代码依赖关系
  • 跨文件进行修改

常用交互模式

模式1:直接命令

创建README.md文件
添加Git忽略规则
格式化所有Python文件
运行测试

模式2:详细描述

我想创建一个React组件,用于显示用户列表。
组件需要:
1. 从API获取用户数据
2. 显示加载状态
3. 处理错误情况
4. 支持分页

模式3:增量改进

你: 创建一个简单的登录表单

Claude: [创建基础表单]

你: 添加表单验证

Claude: [添加验证逻辑]

你: 添加提交后的loading状态

Claude: [添加loading状态]

你: 美化样式

Claude: [添加CSS样式]

实用技巧

技巧1:明确你的需求

❌ 不好的提问:

写个函数

✅ 好的提问:

创建一个函数,接收用户ID,从数据库获取用户信息,
如果用户不存在返回null,包含错误处理

技巧2:分步骤进行

复杂任务分步骤更清晰:

第一步:创建数据模型
第二步:实现CRUD操作
第三步:添加单元测试
第四步:添加API路由

技巧3:提供上下文

我正在用Express和MongoDB开发一个博客系统。
请帮我创建文章(Post)模型,包含标题、内容、作者、创建时间等字段。

技巧4:请求解释

请解释这段代码的工作原理
这个函数为什么这样写?
有更好的实现方式吗?

技巧5:使用深度思考

复杂问题,可以要求深度思考:

think hard: 如何优化这个查询性能?
ultrathink: 设计一个可扩展的微服务架构

多轮对话示例

看一个完整的多轮对话实例:

👤 你: 创建一个待办事项应用的后端API

🤖 Claude: I'll create a Todo API backend for you.
Let me start by setting up the project structure.

[创建文件:server.js, models/Todo.js, routes/todos.js]

✓ Created basic Express server
✓ Created Todo model with Mongoose
✓ Created CRUD routes for todos

────────────────────────────────────────────
👤 你: 添加用户认证功能

🤖 Claude: I'll add authentication to your Todo API.

[创建文件:models/User.js, middleware/auth.js, routes/auth.js]
[修改:todos.js routes to include authentication]

✓ Added User model
✓ Implemented JWT authentication
✓ Protected todo routes
✓ Added login/register endpoints

────────────────────────────────────────────
你: 添加单元测试

🤖 Claude: I'll add unit tests for your API.

[创建文件:tests/auth.test.js, tests/todos.test.js]
[修改:package.json to add test scripts]

✓ Added test suite with Jest
✓ Created tests for authentication
✓ Created tests for todo CRUD operations
✓ Added npm test script

────────────────────────────────────────────
👤 你: 创建API文档

🤖 Claude: I'll generate API documentation.

[创建文件:API.md, swagger.yaml]

✓ Created comprehensive API documentation
✓ Added Swagger/OpenAPI spec
✓ Documented all endpoints with examples

退出和重启

退出Claude Code

# 输入exit或quit
exit

# 或使用快捷键
Ctrl + D (Linux/macOS)
Ctrl + C (所有平台)

保存对话历史

Claude Code会自动保存对话历史,下次启动时可以继续:

# 启动后,使用/history查看历史
claude
/history

下一步探索

完成第一次使用后:

  1. 学习更多命令

  2. 探索核心功能

  3. 尝试实战项目

  4. 进阶配置

常见问题

Q: Claude Code没有响应怎么办?

检查网络连接,确认API密钥有效:

claude --auth-status

Q: 如何查看Claude Code创建或修改了哪些文件?

使用Git查看更改:

git status
git diff

Q: 可以撤销Claude Code的修改吗?

是的,使用Git:

git checkout -- filename  # 撤销单个文件
git reset --hard # 撤销所有更改

Q: Claude Code会自动保存文件吗?

是的,Claude Code会自动保存所有修改。建议配合Git使用,方便回滚。

Q: 一次对话可以处理多少文件?

Claude Code支持约200,000 tokens的上下文,可以同时处理几十个文件。

实用建议

  1. 配合Git使用

    • 在使用Claude Code前先提交当前更改
    • 方便回滚和查看修改历史
  2. 保持清晰沟通

    • 明确表达你的需求
    • 提供必要的上下文
    • 分步骤处理复杂任务
  3. 验证结果

    • Claude Code很强大,但仍需验证
    • 运行测试确保代码正确
    • 检查生成的代码是否符合预期
  4. 利用多轮对话

    • 不要期望一次就完美
    • 通过多轮对话逐步完善
    • 及时提供反馈
  5. 学习提示词技巧

    • 观察什么样的提问得到更好的结果
    • 积累你的提示词模板
    • 查看 最佳实践

总结

通过这第一次使用体验,你应该已经:

✅ 了解如何启动Claude Code ✅ 掌握基本的对话交互方式 ✅ 学会创建和修改文件 ✅ 理解Claude Code的工作流程 ✅ 知道如何提出更好的问题

Claude Code是一个强大的AI编程助手,它会随着你的使用越来越得心应手。继续探索,享受AI赋能的编程体验吧!

参考资源