Refactoring sprawling codebases manually? Harness Claude Code's power in VS Code with custom commands to automate AI-driven refactors across TypeScript and Python projects—saving hours of drudgery.
Large codebases are a fact of life for most developers. Whether you're migrating from class components to hooks in a legacy TypeScript React app or standardizing Python code to use dataclasses, manual refactoring is error-prone, time-consuming, and soul-crushing. Enter Claude Code, Anthropic's CLI powerhouse for AI-assisted coding, now supercharged in VS Code via custom commands.
In this guide, we'll walk through setting up Claude Code in VS Code, crafting custom commands for mass refactors, and applying them to real-world TypeScript and Python examples. By the end, you'll refactor entire directories in minutes, not days.
Picture this: A 50k+ LOC TypeScript monorepo with outdated patterns, or a Python service riddled with namedtuple hacks. Common pain points include:
Traditional tools like sed or IDE find-replace fall short. IDE refactoring wizards choke on complexity. That's where Claude Code shines—leveraging Claude 3.5 Sonnet's superior reasoning for precise, context-aware edits.
Claude Code is Anthropic's CLI tool (claude-code) for AI-powered development workflows. Key features:
Install via npm i -g @anthropic-ai/claude-code (or equivalent; check official docs).
VS Code doesn't have an official Claude Code extension yet, but we bridge this with Tasks and Terminal integrations. For pro users, we'll use the Continue extension (which supports Claude) or custom tasks.json to run claude-code commands.
export ANTHROPIC_API_KEY=sk-...)Create .vscode/tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "Claude Code: Refactor Dir",
"type": "shell",
"command": "claude-code",
"args": [
"refactor",
"${input:targetDir}",
"--prompt",
"${input:prompt}",
"--model",
"claude-3-5-sonnet-20240620",
"--dry-run"
],
"group": "build",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
}
}
],
"inputs": [
{
"id": "targetDir",
"description": "Directory to refactor",
"default": "./src",
"type": "promptString"
},
{
"id": "prompt",
"description": "Refactor prompt",
"default": "Refactor to modern patterns",
"type": "promptString"
}
]
}
Run via Ctrl+Shift+P > Tasks: Run Task > Claude Code: Refactor Dir.
Elevate with keybindings in .vscode/keybindings.json:
[
{
"key": "ctrl+shift+r",
"command": "workbench.action.tasks.runTask",
"args": "Claude Code: TS Hooks Refactor"
}
]
We'll define specialized tasks next.
Scenario: Legacy React app with 200+ class components. Goal: Convert to functional components with hooks.
Add to tasks.json:
{
"label": "Claude Code: TS Hooks Refactor",
"type": "shell",
"command": "claude-code",
"args": [
"refactor",
"${input:tsDir}",
"--prompt",
"Convert all class-based React components to functional components using hooks. Preserve state, lifecycle (useEffect for componentDidMount/Update), props. Update imports. Handle error boundaries if present. Output diffs only for files with changes.",
"--glob",
"**/*.tsx",
"--model",
"claude-3-5-sonnet-20240620",
"--dry-run",
"--approval",
"--output",
"./refactor_diffs.patch"
]
}
Ctrl+Shift+P > Run Task > Claude Code: TS Hooks Refactor../src/components../refactor_diffs.patch in VS Code's Git diff view (Ctrl+Shift+G).--dry-run.Before (UserProfile.tsx):
import React from 'react';
class UserProfile extends React.Component {
state = { user: null };
componentDidMount() {
fetchUser(this.props.id);
}
render() {
return <div>{this.state.user?.name}</div>;
}
}
export default UserProfile;
After (Claude-generated):
import React, { useState, useEffect } from 'react';
const UserProfile = ({ id }) => {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
return <div>{user?.name}</div>;
};
export default UserProfile;
Claude handles edge cases like componentWillUnmount (cleanup in useEffect), context consumers, and HOCs automatically.
Pro Tip: Chain with ESLint: Add post-task to lint --fix.
Scenario: Microservice with 100+ namedtuple and dict-based configs. Migrate to dataclasses for type safety and mutability.
{
"label": "Claude Code: Python Dataclass Refactor",
"type": "shell",
"command": "claude-code",
"args": [
"refactor",
"${input:pyDir}",
"--prompt",
"Replace all namedtuple, collections.namedtuple, and ad-hoc dict classes with @dataclasses.dataclass. Add type hints from context. Preserve __init__, methods, defaults. Update usages. Import from dataclasses. Handle frozen=True if immutable needed. Black-format output.",
"--glob",
"**/*.py",
"--model",
"claude-3-5-sonnet-20240620",
"--dry-run",
"--mypy-check",
"--output",
"./py_refactor_diffs.patch"
]
}
Note: --mypy-check flag (if supported) validates types pre-apply.
Before (config.py):
from collections import namedtuple
UserConfig = namedtuple('UserConfig', ['name', 'email', 'role'])
config = UserConfig('Alice', 'alice@example.com', 'admin')
After:
from dataclasses import dataclass
from typing import Optional
@dataclass
class UserConfig:
name: str
email: str
role: str = 'user'
config = UserConfig(name='Alice', email='alice@example.com')
Claude infers types from usages, adds field(default=...) for optionals, and propagates changes to callers.
MCP Servers: Pair with Model Context Protocol servers for repo-wide context (e.g., load entire monorepo graph).
claude-code refactor ./ --mcp-server ./my-mcp-server
Batch Processing: Use --parallel 4 for multi-file speed.
Git Integration: Auto-commit via --git-commit "Refactor: hooks migration".
Prompt Tuning: Prefix with codebase stats: "Repo: 50k LOC TS, React 18. Analyze first."
Error Handling: --retry 3 --max-tokens 128k for Sonnet's context window.
VS Code Extension Boost: Install Continue.dev for Claude autocomplete + CLI synergy.
--glob "**/test/*".--stats.Custom Claude Code commands in VS Code transform refactoring from a marathon to a sprint. With TypeScript hooks migrations and Python dataclass upgrades under your belt, scale to any codebase challenge. Experiment, iterate prompts, and share your custom tasks on Claude Directory forums.
Next Steps:
tasks.json for your stack.Word count: ~1450. Questions? Comment below.
Build natural voice agents combining Claude API's superior reasoning with ElevenLabs' lifelike TTS. This end-to-end guide creates a conversational web app with STT, AI chat, and speech synthesis.
As data volumes explode in 2025, choosing between Claude's reasoning depth and Mistral Large 2's efficiency is critical. We benchmark SQL generation, visualizations, and large datasets to reveal the w
In the high-stakes world of cybersecurity, rapid threat modeling and incident response can mean the difference between containment and catastrophe. Discover how Claude Enterprise empowers security tea
Build blazing-fast smart contract auditing agents in Rust using the Claude SDK. Harness Claude's reasoning to scan Solidity code for vulnerabilities like reentrancy and overflows.
Elevate team productivity with Claude Artifacts in multi-user projects—enable real-time iterative editing for code reviews and docs without leaving the interface.
Unlock lightning-fast, cost-effective product recommendations for your e-commerce store using Claude 3 Haiku embeddings. This playbook delivers a complete Node.js tutorial to build personalized recomm
Workflows from the Neura Market marketplace related to this Claude resource