Bundle Analysis and Optimization with Claude Code
Learn about bundle analysis and optimization using Claude Code. Includes practical code examples.
Slim Down Your App With Bundle Analysis
Bloated JavaScript bundles directly impact page load time. With Claude Code, you can efficiently go from analysis to implementing optimization measures.
Visualizing Bundle Size
> Analyze the bundle size and identify dependencies that need optimization.
> Also add a configuration that visualizes the bundle as a treemap.
// vite.config.ts
import { defineConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';
export default defineConfig({
plugins: [
visualizer({
filename: 'dist/bundle-stats.html',
open: true,
gzipSize: true,
brotliSize: true,
template: 'treemap',
}),
],
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['react', 'react-dom'],
router: ['react-router-dom'],
ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
},
},
},
},
});
Automatically Checking Bundle Size
// scripts/check-bundle-size.ts
import { readFileSync, readdirSync, statSync } from 'fs';
import path from 'path';
import { gzipSync, brotliCompressSync } from 'zlib';
interface BundleReport {
file: string;
raw: number;
gzip: number;
brotli: number;
}
function analyzeBundles(dir: string): BundleReport[] {
const files = readdirSync(dir, { recursive: true }) as string[];
return files
.filter(f => /\.(js|css)$/.test(f))
.map(file => {
const filePath = path.join(dir, file);
const content = readFileSync(filePath);
return {
file,
raw: content.length,
gzip: gzipSync(content).length,
brotli: brotliCompressSync(content).length,
};
})
.sort((a, b) => b.gzip - a.gzip);
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes}B`;
return `${(bytes / 1024).toFixed(1)}kB`;
}
const reports = analyzeBundles('dist/assets');
console.log('\nBundle size report\n');
console.log('File | Raw | Gzip | Brotli');
console.log('--- | --- | --- | ---');
let totalGzip = 0;
for (const r of reports) {
totalGzip += r.gzip;
console.log(`${r.file} | ${formatSize(r.raw)} | ${formatSize(r.gzip)} | ${formatSize(r.brotli)}`);
}
console.log(`\nTotal (gzip): ${formatSize(totalGzip)}`);
// Enforce a size limit
const LIMIT = 200 * 1024; // 200kB
if (totalGzip > LIMIT) {
console.error(`\nBundle size exceeds the limit (${formatSize(LIMIT)})!`);
process.exit(1);
}
Finding and Replacing Heavy Dependencies
> Suggest replacements for heavy dependencies with lighter alternatives.
// Common replacement patterns
const replacements = {
// moment.js (300kB) -> dayjs (2kB)
'moment': 'dayjs',
// lodash (70kB) -> lodash-es (tree-shakable)
'lodash': 'lodash-es',
// axios (13kB) -> fetch API (built-in)
'axios': 'native fetch',
// uuid (3.5kB) -> crypto.randomUUID() (built-in)
'uuid': 'crypto.randomUUID()',
};
// Per-function imports from lodash
// BAD: import _ from 'lodash';
// GOOD: import debounce from 'lodash-es/debounce';
Code Splitting via Dynamic Imports
// Route-based splitting
const routes = [
{
path: '/dashboard',
component: lazy(() => import('./pages/Dashboard')),
},
{
path: '/settings',
component: lazy(() => import('./pages/Settings')),
},
];
// Conditional imports
async function loadEditor() {
const { EditorModule } = await import('./modules/heavy-editor');
return new EditorModule();
}
// Lazy loading a library
async function highlightCode(code: string, lang: string) {
const { highlight } = await import('prismjs');
return highlight(code, lang);
}
Monitoring Bundle Size in CI/CD
# .github/workflows/bundle-check.yml
name: Bundle Size Check
on: [pull_request]
jobs:
bundle-size:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
- run: npx tsx scripts/check-bundle-size.ts
- uses: actions/upload-artifact@v4
with:
name: bundle-report
path: dist/bundle-stats.html
Summary
Bundle analysis and optimization are closely tied to tree shaking. With Claude Code, you can efficiently analyze dependencies and replace them with lighter alternatives. Integrating bundle size checks into your CI/CD helps prevent performance regressions. For Vite build optimization, see the official Vite documentation.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Key commands, shortcuts, and prompt examples on a single printable page.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
Getting Started with Claude Code Agent SDK — Build Autonomous Agents Fast
Learn how to build autonomous AI agents with Claude Code Agent SDK. Covers setup, tool definitions, and multi-step execution with practical code examples.
The Complete Guide to Context Management in Claude Code
Learn practical techniques to maximize Claude Code's context window. Covers token optimization, conversation splitting, and CLAUDE.md usage.
Mastering Claude Code Hooks: Auto-Format, Auto-Test, and More
Mastering Claude Code Hooks: Auto-Format, Auto-Test, and More. A practical guide with code examples.