refactor について
Refactorは、AIの提案とASTツールを使った体系的なコードリファクタリングを支援するスキルです。一般的な変換を扱い、動作を保つために小さな変更をテストしながら進めます。
主な機能
- 01AIによるリファクタリング分析
- 02JavaScriptからTypeScriptへの変換支援
- 03ReactクラスからHooksへの変換支援
- 04AST変換による名前変更
- 05テストを伴う段階的なワークフロー
活用シーン
- 01レガシーコードの安全な変更を計画
- 02重複コードや複雑な関数を特定
- 03AST変換でコードシンボルの名前を変更
インストール
コマンドをコピーしてターミナルで実行します。
$
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/
ベストプラクティス
- 最初にテストする - テストされていないコードはリファクタリングしないでください
- 小さなステップで進める - 一度に変更するのは 1 つだけです
- こまめにコミットする - 動作する状態ごとにコミットします
- 動作を維持する - リファクタリングは書き直しではありません
- ツールを使う - AST 変換 > 検索と置換
- 差分をレビューする - 変更のたびに検証します
- 継続的にテストを実行する - 問題を早期に検出します
コメント
Markdown 対応