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
Related Posts
Advanced
Advanced
Claude Code MCP Server 설정 및 실전 활용 가이드
Claude Code의 MCP Server 기능을 종합적으로 소개합니다. 외부 도구 연결, 서버 설정, 실전 통합 사례까지 한 번에 알아보세요.
Advanced
Advanced
Claude Code Hooks 완전 정복: 자동 포맷팅, 자동 테스트 설정법
Claude Code Hooks로 자동 포맷팅과 자동 테스트를 설정하는 방법을 알아봅니다. 실용적인 설정 예제와 실전 활용 사례를 포함합니다.
Advanced
Advanced
CLAUDE.md 작성 완벽 가이드: 프로젝트 설정 베스트 프랙티스
효과적인 CLAUDE.md 파일 작성법을 상세히 소개합니다. 기술 스택, 컨벤션, 프로젝트 구조를 Claude Code에 전달하여 출력 품질을 극대화하세요.