Advanced

优化Tree Shaking:Claude Code 实战指南

了解optimizing tree shaking:Claude Code 实战. 包含实用代码示例。

Tree Shakingで不要コードを自動除去

Tree Shakingは、使われていないコードを打包から自動的に除去する优化技術です。借助 Claude Code,Tree Shakingが有效地動作するコード構造への改善を高效地実施可以。

Tree Shakingが効く書き方

> Tree Shakingが最大限効くように、ユーティリティ模块を重构して。
// ❌ Tree Shakingが効かない書き方
// utils/index.ts
export default {
  formatDate(date: Date) { /* ... */ },
  formatCurrency(amount: number) { /* ... */ },
  formatPhoneNumber(phone: string) { /* ... */ },
  truncateText(text: string, max: number) { /* ... */ },
};

// ✅ Tree Shakingが効く書き方
// 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';

// ✅ 直接导入(確実にTree Shakingされる)
import { Button } from './components/Button';

库のTree Shaking支持确认

// 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のTree Shakingを确认
await checkTreeShaking('lodash-es', 'debounce');
await checkTreeShaking('lodash-es', 'merge');

CommonJSからESModulesへの移行

// ❌ CommonJS(Tree Shaking不可)
const { pick, omit } = require('lodash');
module.exports = { myFunction };

// ✅ ESModules(Tree Shaking可能)
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,
      },
    },
  },
});

Tree Shakingの効果を測定

# バンドルサイズの比較
npx vite build -- --mode analyze

# 特定のインポートのサイズ確認
npx import-cost

总结

Tree Shakingは打包分析と組み合わせることで最大の効果を発揮します。借助 Claude Code,CommonJSからESModulesへの移行やバレル文件の优化など、地道な重构作業を效率化可以。代码分割と併用して、应用全体のロード时间を短縮吧。Tree Shakingの仕組み相关内容请参阅webpack官方文档也可以作为参考。

#Claude Code #tree shaking #バンドル #ESModules #optimization