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
Claude Code 워크플로우를 한 단계 업그레이드하세요
지금 바로 Claude Code에 복사해 쓸 수 있는 검증된 프롬프트 템플릿 50선.
M
이 글을 작성한 사람
Masa
Claude Code를 적극 활용하는 엔지니어. 10개 언어, 2,000페이지 이상의 테크 미디어 claudecode-lab.com을 운영 중.
관련 글
Advanced
Claude Code Agent SDK 입문 ― 자율 에이전트를 빠르게 구축하는 방법
Claude Code Agent SDK로 자율형 AI 에이전트를 구축하는 방법을 해설합니다. 설정부터 도구 정의, 멀티스텝 실행까지 실전 코드와 함께 소개합니다.
Advanced
Claude Code 컨텍스트 관리 테크닉 완전 가이드
Claude Code의 컨텍스트 윈도우를 최대한 활용하는 실전 테크닉을 해설합니다. 토큰 절약, 대화 분할, CLAUDE.md 활용법까지 소개합니다.
Advanced
Claude Code MCP Server 설정 및 실전 활용 가이드
Claude Code의 MCP Server 기능을 종합적으로 소개합니다. 외부 도구 연결, 서버 설정, 실전 통합 사례까지 한 번에 알아보세요.