Bundle Analysis and Optimization: Claude Code 활용 가이드
bundle analysis and optimization: Claude Code 활용. 실용적인 코드 예시를 포함합니다.
번들分析で앱の軽量化を実現
JavaScript번들の肥大化は、페이지の로딩速度に直接影響します。Claude Code를 활용하면 번들分析から최적화施策の구현まで효율적으로進められます。
번들サイズの可視化
> 번들サイズを分析して、최적화すべき依存関係を特定して。
> 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'],
},
},
},
},
});
번들サイズの自動チェック
// 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('\n📦 バンドルサイズレポート\n');
console.log('ファイル | 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(`\n合計 (gzip): ${formatSize(totalGzip)}`);
// サイズ上限チェック
const LIMIT = 200 * 1024; // 200kB
if (totalGzip > LIMIT) {
console.error(`\n❌ バンドルサイズが上限(${formatSize(LIMIT)})を超えています!`);
process.exit(1);
}
重い依存関係の特定と代替
> 大きな依存関係を軽量な代替に置き換える提案をして。
// よくある置き換えパターン
const replacements = {
// moment.js (300kB) → dayjs (2kB)
'moment': 'dayjs',
// lodash (70kB) → lodash-es(tree-shaking대응)
'lodash': 'lodash-es',
// axios (13kB) → fetch API(組み込み)
'axios': 'native fetch',
// uuid (3.5kB) → crypto.randomUUID()(組み込み)
'uuid': 'crypto.randomUUID()',
};
// lodashの個別가져오기
// ❌ import _ from 'lodash';
// ✅ import debounce from 'lodash-es/debounce';
動的가져오기에 의한코드 분할
// ルートベースの分割
const routes = [
{
path: '/dashboard',
component: lazy(() => import('./pages/Dashboard')),
},
{
path: '/settings',
component: lazy(() => import('./pages/Settings')),
},
];
// 条件付き가져오기
async function loadEditor() {
const { EditorModule } = await import('./modules/heavy-editor');
return new EditorModule();
}
// 라이브러리の지연 로딩
async function highlightCode(code: string, lang: string) {
const { highlight } = await import('prismjs');
return highlight(code, lang);
}
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
정리
번들分析と최적화は、트리 쉐이킹と密接に関連しています。Claude Code를 활용하면 依存関係の分析から軽量な代替への置き換えまで효율적으로実施할 수 있습니다。CI/CDに번들サイズチェックを組み込むことで、성능の劣化を未然に防げます。Viteの빌드최적화에 대해서는Vite공식 문서를 참고하세요.
#Claude Code
#bundle analysis
#Webpack
#Vite
#performance
무료 제공
무료 PDF: 5분 완성 Claude Code 치트시트
이메일 주소만 등록하시면 A4 한 장짜리 치트시트 PDF를 즉시 보내드립니다.
개인정보는 엄격하게 관리하며 스팸은 보내지 않습니다.
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Advanced
Claude Code/Codex 안전 Agent Harness 설계: 권한, 검증, 롤백
Claude Code와 Codex를 안전하게 운영하기 위한 Agent Harness를 권한 정책, 실행 계획, 검증, 복구 계층으로 설계합니다.
Advanced
Claude Code 서브에이전트 활용 패턴 10선
Claude Code의 서브에이전트 기능을 활용하는 10가지 실전 패턴. 병렬 처리, 전문화, 컨텍스트 분리로 개발 속도를 두 배로 만드는 방법.
Advanced
Claude Code Agent SDK 입문 ― 자율 에이전트를 빠르게 구축하는 방법
Claude Code Agent SDK로 자율형 AI 에이전트를 구축하는 방법을 해설합니다. 설정부터 도구 정의, 멀티스텝 실행까지 실전 코드와 함께 소개합니다.