Optimizing Tree Shaking: Claude Code 활용 가이드
optimizing tree shaking: Claude Code 활용. 실용적인 코드 예시를 포함합니다.
트리 쉐이킹で不要コードを自動除去
트리 쉐이킹は、使われていないコードを번들から自動的に除去する최적화技術です。Claude Code를 활용하면 트리 쉐이킹が효과적으로動作するコード構造への改善を효율적으로実施할 수 있습니다。
트리 쉐이킹が効く書き方
> 트리 쉐이킹が最大限効くように、ユーティリティ모듈を리팩터링して。
// ❌ 트리 쉐이킹が効かない書き方
// utils/index.ts
export default {
formatDate(date: Date) { /* ... */ },
formatCurrency(amount: number) { /* ... */ },
formatPhoneNumber(phone: string) { /* ... */ },
truncateText(text: string, max: number) { /* ... */ },
};
// ✅ 트리 쉐이킹が効く書き方
// utils/formatDate.ts
export function formatDate(date: Date): string {
return new Intl.DateTimeFormat('en-US').format(date);
}
// utils/formatCurrency.ts
export function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'JPY' }).format(amount);
}
// utils/index.ts(再내보내기)
export { formatDate } from './formatDate';
export { formatCurrency } from './formatCurrency';
export { formatPhoneNumber } from './formatPhoneNumber';
export { truncateText } from './truncateText';
sideEffectsの설정
// package.json
{
"name": "my-library",
"sideEffects": false
}
// CSS가져오기がある場合
{
"sideEffects": [
"*.css",
"*.scss",
"./src/polyfills.ts",
"./src/global-setup.ts"
]
}
バレル파일の최적화
// ❌ 巨大なバレル파일(全모듈を読み込む)
// components/index.ts
export { Button } from './Button';
export { Card } from './Card';
export { Modal } from './Modal';
export { Table } from './Table';
export { Tabs } from './Tabs';
// ... 100個の컴포넌트
// ❌ 이가져오기は全컴포넌트を読み込む可能性がある
import { Button } from './components';
// ✅ 直接가져오기(確実に트리 쉐이킹される)
import { Button } from './components/Button';
라이브러리の트리 쉐이킹대응확인
// scripts/check-tree-shaking.ts
import { build } from 'esbuild';
import { readFileSync } from 'fs';
async function checkTreeShaking(pkg: string, importName: string) {
const entry = `import { ${importName} } from '${pkg}'; console.log(${importName});`;
const result = await build({
stdin: { contents: entry, resolveDir: process.cwd() },
bundle: true,
write: false,
minify: true,
treeShaking: true,
format: 'esm',
metafile: true,
});
const size = result.outputFiles[0].contents.length;
console.log(`${pkg} → ${importName}: ${(size / 1024).toFixed(1)}kB`);
return size;
}
// Usage example:lodash-esの트리 쉐이킹を확인
await checkTreeShaking('lodash-es', 'debounce');
await checkTreeShaking('lodash-es', 'merge');
CommonJSからESModulesへの移行
// ❌ CommonJS(트리 쉐이킹不可)
const { pick, omit } = require('lodash');
module.exports = { myFunction };
// ✅ ESModules(트리 쉐이킹可能)
import { pick, omit } from 'lodash-es';
export function myFunction() { /* ... */ }
// tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2020"
}
}
動的가져오기との組み合わせ
// 条件付きで重い라이브러리を読み込む
async function processMarkdown(content: string) {
// 必要なときだけ가져오기
const { unified } = await import('unified');
const remarkParse = (await import('remark-parse')).default;
const remarkHtml = (await import('remark-html')).default;
const result = await unified()
.use(remarkParse)
.use(remarkHtml)
.process(content);
return result.toString();
}
Viteでの설정최적화
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
build: {
target: 'es2020',
minify: 'terser',
terserOptions: {
compress: {
dead_code: true,
drop_console: true, // console.logを除去
pure_funcs: ['console.debug'], // 特定함수を除去
},
},
rollupOptions: {
treeshake: {
moduleSideEffects: false,
propertyReadSideEffects: false,
},
},
},
});
트리 쉐이킹の効果を測定
# バンドルサイズの比較
npx vite build -- --mode analyze
# 特定のインポートのサイズ確認
npx import-cost
정리
트리 쉐이킹は번들分析と組み合わせることで最大の効果を発揮します。Claude Code를 활용하면 CommonJSからESModulesへの移行やバレル파일の최적화など、地道な리팩터링作業を효율화할 수 있습니다。코드 분할と併用して、앱全体のロード시간を短縮합시다。트리 쉐이킹の仕組み에 대해서는webpack공식 문서도 참고가 됩니다.
#Claude Code
#tree shaking
#バンドル
#ESModules
#optimization
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 기능을 종합적으로 소개합니다. 외부 도구 연결, 서버 설정, 실전 통합 사례까지 한 번에 알아보세요.