第 10 期 | 文件批处理与重构利器
🎯 学习目标
学完本期你将掌握:
- 跨文件批量重构的指令编写技巧
- 如何让 Claude 用
Glob+Read+Edit完成大规模代码迁移 - Subagent 在并行重构中的应用
- Git Worktree 隔离重构的安全策略
📖 核心概念讲解
10.1 批量重构的三种模式
模式 1: 顺序重构 (Sequential)
Claude 逐个打开文件,依次修改
适合: 10 个以内的文件
特点: 慢但精确
模式 2: 子代理并行 (Subagent Parallel)
Claude 启动多个子代理 (TaskCreate),各自处理不同文件
适合: 大量独立文件
特点: 快速,但每个子代理的上下文较小
模式 3: Worktree 隔离 (Git Worktree)
在新的 Worktree 分支中执行重构
适合: 高风险重构(随时可以回滚一整个分支)
特点: 最安全,不影响主分支
10.2 重构工具链
典型的重构工具调用链:
Glob("**/*.ts") → 发现所有目标文件
│
Grep("oldImport" in **) → 定位需要修改的文件
│
Read(file1.ts) → 读取文件理解上下文
│
Edit(file1.ts) → 精准修改
│
Bash("npm run lint") → 验证修改无语法错误
│
Bash("npm test") → 运行测试确认无回归
💻 模拟 Claude TUI 交互
场景 1:批量迁移 import 路径
> 我们的项目从 @/utils 改为 @/lib/utils,
请把所有文件中的 import 路径都更新
╭─ Claude ─────────────────────────────────────────────╮
│ │
│ 🔍 Tool: Grep ("from '@/utils" across src/**) │
│ → Found 23 files with matching imports │
│ │
│ 📋 受影响的文件列表: │
│ 1. src/components/UserCard.tsx │
│ 2. src/components/DataTable.tsx │
│ 3. src/hooks/useAuth.ts │
│ 4. src/api/routes/users.ts │
│ ... 共 23 个文件 │
│ │
│ 我将逐个修改这些文件中的 import 路径。 │
│ │
│ ⚙️ Tool: Edit → src/components/UserCard.tsx │
│ ╭─ DIFF ─────────────────────────────────────╮ │
│ │ - import { formatDate } from '@/utils'; │ │
│ │ - import { cn } from '@/utils/classnames'; │ │
│ │ + import { formatDate } from '@/lib/utils'; │ │
│ │ + import { cn } │ │
│ │ + from '@/lib/utils/classnames'; │ │
│ ╰─────────────────────────────────────────────╯ │
│ │
│ ⚙️ Tool: Edit → src/components/DataTable.tsx │
│ ✅ Updated (1 import changed) │
│ │
│ ⚙️ Tool: Edit → src/hooks/useAuth.ts │
│ ✅ Updated (2 imports changed) │
│ │
│ ... (逐个处理所有 23 个文件) │
│ │
│ ⚙️ Tool: Bash │
│ $ npx tsc --noEmit │
│ ✅ No errors found │
│ │
│ ⚙️ Tool: Bash │
│ $ npm test │
│ ✅ 147 tests passed, 0 failed │
│ │
│ 🎉 全部 23 个文件已更新! │
│ TypeScript 编译通过,所有测试通过。 │
│ │
╰──────────────────────────────────────────────────────╯
场景 2:使用 Git Worktree 隔离高风险重构
> 把所有的 class component 重构为 function component,
这是个大改动,请在独立分支上进行
╭─ Claude ─────────────────────────────────────────────╮
│ │
│ 好的,我先创建一个 Git Worktree 来隔离这次重构。 │
│ │
│ ⚙️ Tool: EnterWorktree │
│ Branch: refactor/class-to-function │
│ Path: ../my-project-worktree-refactor │
│ ✅ Worktree created and switched │
│ │
│ 现在我在隔离的分支上工作,主分支不受影响。 │
│ │
│ 🔍 Tool: Grep ("extends Component\|extends │
│ React.Component" across src/**) │
│ → Found 8 class components │
│ │
│ 📋 需要重构的组件: │
│ 1. src/components/Header.tsx (47 lines) │
│ 2. src/components/Sidebar.tsx (92 lines) │
│ 3. src/components/Modal.tsx (65 lines) │
│ ... 共 8 个组件 │
│ │
│ 开始逐个重构... │
│ │
│ ⚙️ Tool: Read → src/components/Header.tsx │
│ ⚙️ Tool: Edit → src/components/Header.tsx │
│ ╭─ DIFF (摘要) ─────────────────────────────╮ │
│ │ - class Header extends React.Component { │ │
│ │ - state = { isOpen: false }; │ │
│ │ - render() { ... } │ │
│ │ + export function Header() { │ │
│ │ + const [isOpen, setIsOpen] = │ │
│ │ + useState(false); │ │
│ │ + return ( ... ); │ │
│ │ + } │ │
│ ╰─────────────────────────────────────────────╯ │
│ ✅ Header: class → function ✓ │
│ │
│ ... (逐个处理所有 8 个组件) │
│ │
│ ⚙️ Tool: Bash │
│ $ npm test │
│ ✅ All 147 tests passed │
│ │
│ ⚙️ Tool: Bash │
│ $ git add -A && git commit -m │
│ "refactor: convert 8 class components │
│ to function components" │
│ ✅ Committed │
│ │
│ ⚙️ Tool: ExitWorktree │
│ ✅ Back to main branch │
│ │
│ 🎉 重构完成!结果在分支 │
│ 'refactor/class-to-function' 上。 │
│ 你可以 code review 后决定是否合并。 │
│ │
╰──────────────────────────────────────────────────────╯
💻 代码演示:批量处理命令行用法
# ✅ 批量替换(Print Mode)
claude -p "把项目中所有 console.log 替换为 structured logger"
# ✅ 批量添加错误处理
claude -p "给 src/routes/ 下所有路由处理函数添加 try-catch"
# ✅ 批量添加类型注解
claude -p "给 src/utils/ 下所有函数添加 TypeScript 类型注解"
# ✅ 代码现代化迁移
claude -p "把所有 CommonJS require() 改为 ES Module import"
# ✅ API 版本迁移
claude -p "把所有调用 axios 的地方改为使用 fetch API"
使用子代理并行处理
# 在 CLAUDE.md 中定义重构子代理
cat > .claude/agents/refactor-agent.md << 'EOF'
---
description: "Handles file-level refactoring tasks. Use when
asked to refactor, migrate, or transform code across
multiple files."
allowed_tools:
- Read
- Edit
- Glob
- Grep
- Bash
---
# Refactoring Agent
## Instructions
1. Read the target file
2. Apply the requested transformation
3. Run `npx tsc --noEmit` to verify
4. Report success or failure
EOF
🔧 涉及的 Tools
| 工具 | 重构阶段 | 作用 |
|---|---|---|
Glob |
发现 | 找到所有需要修改的文件 |
Grep |
定位 | 搜索需要替换的代码模式 |
Read |
理解 | 读取文件内容理解上下文 |
Edit |
修改 | 精准编辑特定行 |
Bash |
验证 | 运行 tsc、测试、lint |
EnterWorktree |
隔离 | 创建 Git Worktree |
ExitWorktree |
回归 | 退出 Worktree |
TaskCreate |
并行 | 创建子任务并行处理 |
📝 本期要点回顾
- 批量重构遵循 发现 → 定位 → 理解 → 修改 → 验证 的流程
- 小规模重构(<10 文件)用 顺序模式 就够了
- 高风险重构优先使用 Git Worktree 隔离
- 每次修改后都应该 运行测试,确保无回归
- 使用
--allowedTools限制只允许Edit,防止误执行危险命令