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
总结
打包分析と优化は、Tree Shakingと密接に関連しています。借助 Claude Code,依存関係の分析から軽量な代替への置き換えまで高效地実施可以。CI/CDに打包サイズチェックを組み込むことで、性能の劣化を未然に防げます。Viteの构建优化相关内容请参阅Vite官方文档。
#Claude Code
#bundle analysis
#Webpack
#Vite
#performance
Related Posts
Advanced
Advanced
Claude Code Hooks 完全指南:自动格式化、自动测试等实用配置
详解如何通过 Claude Code Hooks 实现自动格式化和自动测试。包含实际配置示例和真实使用场景。
Advanced
Advanced
Claude Code MCP Server 配置指南与实战用例
全面介绍 Claude Code 的 MCP Server 功能。从外部工具连接、服务器配置到真实集成案例,一文掌握 MCP 生态。
Advanced
Advanced
CLAUDE.md 编写完全指南:项目配置最佳实践
深入讲解如何编写高效的 CLAUDE.md 文件。学会向 Claude Code 传达你的技术栈、规范和项目结构,最大化输出质量。