Skip to content

基础用法

文件操作

Claude Code 提供强大的文件操作工具,支持读取、写入、编辑等操作。

Read - 读取文件

bash
# 自动读取相关文件
You: 分析 src/app.js 的代码结构

Claude: [使用 Read 工具读取 src/app.js]
Reading src/app.js...
This file contains:
- Express app initialization
- 5 route handlers
- Error middleware

Write - 创建新文件

bash
You: 创建一个新的配置文件 config.yaml

Claude: [使用 Write 工具创建文件]
 Created config.yaml

Edit - 编辑现有文件

bash
You: app.js 中的端口号改为 4000

Claude: [使用 Edit 工具修改文件]
 Updated app.js
  Changed PORT from 3000 to 4000

Glob - 查找文件

bash
You: 找出所有 JavaScript 测试文件

Claude: [使用 Glob 工具]
Found 15 test files:
- src/__tests__/user.test.js
- src/__tests__/auth.test.js
- ...

Grep - 搜索内容

bash
You: 在项目中搜索所有使用 TODO 注释的地方

Claude: [使用 Grep 工具]
Found 8 occurrences of TODO:
- src/api.js:45: // TODO: Add error handling
- src/utils.js:120: // TODO: Optimize performance
- ...

代码生成

生成函数

bash
You: 创建一个函数用于验证邮箱地址

Claude: I'll create an email validation function.
javascript
function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

module.exports = { validateEmail };

生成类

bash
You: 创建一个 User 类,包含 name, email, validate 方法

Claude: I'll create a User class with validation.
javascript
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  validate() {
    if (!this.name || this.name.trim().length === 0) {
      throw new Error('Name is required');
    }
    if (!this.email || !this.email.includes('@')) {
      throw new Error('Valid email is required');
    }
    return true;
  }
}

module.exports = User;

生成 API 端点

bash
You: 创建 REST API 端点处理用户CRUD操作

Claude: I'll create a complete REST API for user management.
javascript
const express = require('express');
const router = express.Router();

// Create
router.post('/users', async (req, res) => {
  // Implementation
});

// Read all
router.get('/users', async (req, res) => {
  // Implementation
});

// Read one
router.get('/users/:id', async (req, res) => {
  // Implementation
});

// Update
router.put('/users/:id', async (req, res) => {
  // Implementation
});

// Delete
router.delete('/users/:id', async (req, res) => {
  // Implementation
});

module.exports = router;

代码重构

提取函数

bash
You: processOrder 函数中的验证逻辑提取为单独的函数

Claude: I'll extract validation logic into a separate function.

Before:
function processOrder(order) {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must have items');
  }
  if (!order.customerId) {
    throw new Error('Customer ID required');
  }
  // Process order...
}

After:
function validateOrder(order) {
  if (!order.items || order.items.length === 0) {
    throw new Error('Order must have items');
  }
  if (!order.customerId) {
    throw new Error('Customer ID required');
  }
}

function processOrder(order) {
  validateOrder(order);
  // Process order...
}

重命名变量

bash
You: userData 重命名为更有意义的 userProfile

Claude: I'll rename userData to userProfile throughout the file.
✓ Renamed 12 occurrences

转换为 ES6

bash
You: user.js 转换为 ES6 语法

Claude: Converting to ES6 syntax...

Before:
var User = function(name) {
  this.name = name;
}

User.prototype.getName = function() {
  return this.name;
}

After:
class User {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }
}

调试与测试

查找 Bug

bash
You: 为什么用户无法登录?

Claude: Let me investigate the login issue.

[Reading auth.js...]
[Reading database.js...]

Found the issue:
- Line 45 in auth.js: password comparison using == instead of bcrypt.compare()
- This bypasses password hashing validation

Recommendation:
Replace:
if (user.password == inputPassword)

With:
if (await bcrypt.compare(inputPassword, user.password))

生成测试

bash
You: calculator.js 生成单元测试

Claude: I'll create comprehensive unit tests.
javascript
const { add, subtract, multiply, divide } = require('./calculator');

describe('Calculator', () => {
  describe('add', () => {
    it('should add two positive numbers', () => {
      expect(add(2, 3)).toBe(5);
    });

    it('should handle negative numbers', () => {
      expect(add(-2, 3)).toBe(1);
    });
  });

  describe('divide', () => {
    it('should divide two numbers', () => {
      expect(divide(6, 2)).toBe(3);
    });

    it('should throw error for division by zero', () => {
      expect(() => divide(5, 0)).toThrow('Division by zero');
    });
  });
});

运行测试

bash
You: 运行所有测试

Claude: [Using Bash tool]
$ npm test

 Calculator tests (4/4 passed)
 User tests (8/8 passed)
 API tests (12/12 passed)

Total: 24 tests passed

Git 操作

查看状态

bash
You: Git 状态如何?

Claude: [Running git status]

On branch: main
Changes not staged:
  - modified: src/app.js
  - modified: src/utils.js

Untracked files:
  - src/new-feature.js

创建提交

bash
You: 提交这些更改

Claude: I'll create a commit with these changes.

[Adding files...]
$ git add src/app.js src/utils.js src/new-feature.js

[Creating commit...]
$ git commit -m "feat: implement new user authentication feature

- Add JWT token generation
- Update login endpoint
- Add auth middleware

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>"

✓ Commit created: abc123def

创建 Pull Request

bash
You: 创建 PR

Claude: I'll create a pull request for this feature.

[Analyzing changes...]
[Pushing to remote...]
$ git push origin feature/auth

[Creating PR...]
$ gh pr create --title "feat: Add user authentication" --body "..."

✓ Pull Request created: #42
https://github.com/user/repo/pull/42

Web 搜索与获取

Web 搜索

bash
You: React 18 的新特性有哪些?

Claude: [Using WebSearch]
Searching for "React 18 new features"...

Based on search results:
1. Automatic Batching
2. Transitions API
3. Suspense for SSR
4. New Hooks (useId, useTransition, useDeferredValue)
...

获取网页内容

bash
You: 获取 Next.js 官方文档关于 API Routes 的内容

Claude: [Using WebFetch]
Fetching: https://nextjs.org/docs/api-routes/introduction

Summary:
- API routes provide backend functionality
- Create files in pages/api directory
- Each file exports a request handler
...

小结

在本章中,我们学习了Claude Code的核心工具集:

  • ✅ 文件操作(Read, Write, Edit, Glob, Grep)
  • ✅ 代码生成(函数、类、API)
  • ✅ 代码重构(提取、重命名、转换)
  • ✅ 调试与测试(查找bug、生成测试、运行测试)
  • ✅ Git 操作(状态、提交、PR)
  • ✅ Web 搜索与获取

关键要点:

  • Claude 智能选择合适的工具
  • 工具可以组合使用
  • 操作前会进行安全确认