# Struggling with Massive Refactors?
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.
## The Refactoring Nightmare in Large Codebases
Picture this: A 50k+ LOC TypeScript monorepo with outdated patterns, or a Python service riddled with `namedtuple` hacks. Common pain points include:
- **Scale**: Thousands of files to touch.
- **Consistency**: Ensuring uniform changes without regressions.
- **Context**: AI needs deep codebase awareness.
- **Safety**: Previewing changes before applying.
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.
## What is Claude Code?
Claude Code is Anthropic's CLI tool (`claude-code`) for AI-powered development workflows. Key features:
- **File/Directory Operations**: Analyze, edit, generate code across repos.
- **Prompt Engineering**: Custom prompts for tasks like refactoring.
- **Model Integration**: Defaults to Claude Opus/Sonnet/Haiku via API.
- **Safety Rails**: Dry-run mode, diff previews, human approval gates.
Install via `npm i -g @anthropic-ai/claude-code` (or equivalent; check [official docs](https://anthropic.com/claude-code)).
## Integrating Claude Code with VS Code
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.
### Step 1: Prerequisites
- VS Code 1.80+
- Claude Code CLI installed and API key set (`export ANTHROPIC_API_KEY=sk-...`)
- Node.js/Python environments matching your project
### Step 2: Basic Task Setup
Create `.vscode/tasks.json`:
```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`.
### Step 3: Custom Commands for Power Users
Elevate with keybindings in `.vscode/keybindings.json`:
```json
[
{
"key": "ctrl+shift+r",
"command": "workbench.action.tasks.runTask",
"args": "Claude Code: TS Hooks Refactor"
}
]
```
We'll define specialized tasks next.
## TypeScript Example: Migrating Class Components to Hooks
**Scenario**: Legacy React app with 200+ class components. Goal: Convert to functional components with hooks.
### Custom Task
Add to `tasks.json`:
```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"
]
}
```
### Running It
1. `Ctrl+Shift+P` > Run Task > `Claude Code: TS Hooks Refactor`.
2. Input dir: `./src/components`.
3. Review `./refactor_diffs.patch` in VS Code's Git diff view (`Ctrl+Shift+G`).
4. Approve: Rerun without `--dry-run`.
### Sample Before/After
**Before (`UserProfile.tsx`)**:
```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)**:
```tsx
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`.
## Python Example: Standardizing to Dataclasses
**Scenario**: Microservice with 100+ `namedtuple` and dict-based configs. Migrate to `dataclasses` for type safety and mutability.
### Custom Task
```json
{
"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.
### Sample Before/After
**Before (`config.py`)**:
```python
from collections import namedtuple
UserConfig = namedtuple('UserConfig', ['name', 'email', 'role'])
config = UserConfig('Alice', '
[email protected]', 'admin')
```
**After**:
```python
from dataclasses import dataclass
from typing import Optional
@dataclass
class UserConfig:
name: str
email: str
role: str = 'user'
config = UserConfig(name='Alice', email='
[email protected]')
```
Claude infers types from usages, adds `field(default=...)` for optionals, and propagates changes to callers.
## Advanced Tips for Enterprise Scale
- **MCP Servers**: Pair with Model Context Protocol servers for repo-wide context (e.g., load entire monorepo graph).
```bash
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](https://continue.dev) for Claude autocomplete + CLI synergy.
## Best Practices
- **Always Dry-Run**: Review diffs in VS Code.
- **Test Subsets**: Start with `--glob "**/test/*"`.
- **Version Control**: Branch before mass refactors.
- **Model Choice**: Sonnet for speed/accuracy; Opus for ultra-complex logic.
- **Prompt Specificity**: Include "Follow Airbnb style" or "PEP8".
- **Metrics**: Track LOC changed, files touched via `--stats`.
## Conclusion
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**:
- Fork this `tasks.json` for your stack.
- Explore Claude API for programmatic refactors.
- Watch Anthropic's roadmap for native VS Code extension.
*Word count: ~1450. Questions? Comment below.*