关于 refactor
Refactor 是一项借助 AI 建议和 AST 工具进行系统化代码重构的技能。它涵盖常见转换,并提倡通过小步测试来保持行为不变。
主要功能
- 01AI 辅助分析重构机会
- 02提供 JavaScript 转 TypeScript 指引
- 03提供 React 类组件转 Hooks 指引
- 04使用 AST 转换进行重命名
- 05采用逐步测试的工作流
适用场景
- 01规划旧代码的安全改动
- 02发现重复代码和复杂函数
- 03使用 AST 转换重命名代码符号
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ johnlindquist/ claude --skill refactor安装后在 Claude Code 中输入/refactor确认已加载。
详细介绍
重构助手
在 AI 指导下进行系统化代码重构。
前提条件
# Gemini for analysis and suggestions
pip install google-generativeai
export GEMINI_API_KEY=your_api_key
# AST-based tools
npm install -g jscodeshift
npm install -g typescript
重构操作
JavaScript 转 TypeScript
# Step 1: Rename file
mv file.js file.ts
# Step 2: AI assistance for types
CODE=$(cat file.ts)
gemini -m pro -o text -e "" "Convert this JavaScript to TypeScript with proper types:
$CODE
Requirements:
- Add explicit types for function parameters and returns
- Create interfaces for object shapes
- Use strict TypeScript (no any unless necessary)
- Preserve functionality exactly"
类转 React Hooks
CODE=$(cat ClassComponent.tsx)
gemini -m pro -o text -e "" "Convert this React class component to functional component with hooks:
$CODE
Requirements:
- Convert state to useState
- Convert lifecycle methods to useEffect
- Convert class methods to functions
- Preserve all functionality
- Use proper TypeScript types"
代码现代化
CODE=$(cat legacy.ts)
gemini -m pro -o text -e "" "Modernize this code to current best practices:
$CODE
Apply:
- ES2023+ features where appropriate
- Modern TypeScript patterns
- Current framework idioms
- Better error handling
- Improved readability"
系统化重命名
# Using sed for simple renames
find src -name "*.ts" -exec sed -i '' 's/oldName/newName/g' {} +
# Using ripgrep to preview
rg "oldName" src/
# With jscodeshift for AST-safe rename
npx jscodeshift -t rename-transform.ts src/
# AI-assisted rename planning
gemini -m pro -o text -e "" "I want to rename 'oldName' to 'newName' across the codebase.
Files that use it:
$(rg -l "oldName" src/)
Suggest:
1. Order of changes to avoid breaks
2. Any tricky cases to watch for
3. Tests to run after"
分析命令
查找重构机会
gemini -m pro -o text -e "" "Analyze this code for refactoring opportunities:
$(cat src/module.ts)
Look for:
- Code duplication
- Long functions
- Deep nesting
- Magic numbers/strings
- Poor naming
- Missing abstractions
- Tight coupling"
复杂度分析
# Find complex functions
rg "function|=>\s*{" src/ -A 50 | head -200
# Ask AI to identify complexity
gemini -m pro -o text -e "" "Identify the most complex functions in this code and suggest simplifications:
$(cat src/complex-file.ts)"
安全重构工作流
第 1 步:确保测试覆盖率
# Check coverage before refactoring
npm test -- --coverage
# Identify untested code
npx jest --coverage --coverageReporters=text | grep -E "^(File|.*\|)"
第 2 步:规划重构
gemini -m pro -o text -e "" "Plan a safe refactoring for:
CURRENT CODE:
$(cat src/file.ts)
GOAL: [what you want to improve]
Provide:
1. Step-by-step plan
2. Risk assessment
3. Rollback strategy
4. Tests to add first"
第 3 步:小而经过测试的变更
# Make one small change
# Run tests
npm test
# Commit if green
git add -A && git commit -m "refactor: [specific change]"
# Repeat
第 4 步:验证行为
# Compare before/after behavior
# Run integration tests
# Manual testing if needed
常见重构
提取函数
gemini -m pro -o text -e "" "Extract a reusable function from this code:
$(cat src/file.ts | sed -n '10,50p')
Create a well-named function with:
- Clear parameters
- Typed return value
- JSDoc comment
- Single responsibility"
简化条件语句
gemini -m pro -o text -e "" "Simplify these conditionals:
\`\`\`typescript
$(rg -A 10 "if.*{" src/file.ts)
\`\`\`
Use:
- Early returns
- Guard clauses
- Lookup tables where appropriate
- Optional chaining"
消除重复
# Find similar code
gemini -m pro -o text -e "" "Find duplicate or similar code patterns in:
$(cat src/*.ts)
Suggest how to DRY it up with:
- Shared functions
- Higher-order functions
- Generics if TypeScript"
jscodeshift 转换
创建转换
// rename-transform.ts
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.Identifier, { name: 'oldName' })
.replaceWith(j.identifier('newName'))
.toSource();
}
运行转换
# Dry run
npx jscodeshift -d -p -t transform.ts src/
# Apply
npx jscodeshift -t transform.ts src/
最佳实践
- 测试先行 - 不要重构未经测试的代码
- 小步前进 - 一次只做一个变更
- 频繁提交 - 每个可工作的状态
- 保持行为 - 重构不是重写
- 使用工具 - AST 转换 > 查找替换
- 审查差异 - 验证每个变更
- 持续运行测试 - 尽早发现中断
评论
支持 Markdown