Nâng CaoBuild Tools iconBuild Tools

Tree shaking deep dive: tại sao một số packages không tree-shakeable?

Tree shaking cần ESM + sideEffects: false trong package.json — lodash dùng CJS nên không tree-shakeable (dùng lodash-es); barrel files (index.ts) có thể phá tree shaking nếu thiếu sideEffects: false.

Tree shaking loại bỏ unused exports dựa trên static analysis của ESM import/export. Điều kiện cần:

  1. ESM format (không phải CJS require)
  2. sideEffects: false trong package.json
  3. không có dynamic imports của cùng module. Tại sao lodash không tree-shakeable: lodash dùng CJS, require('lodash') load toàn bộ — dùng lodash-es hoặc import debounce from 'lodash/debounce' (path import). sideEffects field: nếu không có → bundler giả định mọi module có side effects → không eliminate. 'sideEffects': false cho biết bundler an toàn tree-shake toàn bộ package; 'sideEffects': ['.css', './src/polyfill.js'] exclude files có side effects thật. /#__PURE__/ annotation: đánh dấu function call không có side effects: const App = /#__PURE__*/ createApp() — React compiled output dùng pattern này cho JSX. Named exports vs default exports: named exports (export function foo()) tree-shake tốt hơn default exports (export default { foo, bar }) vì bundler biết chính xác tên. Barrel files (index.ts export từ nhiều files): có thể phá tree shaking nếu có side effects; sideEffects: false trong package.json fix vấn đề này. Kiểm tra: Bundle Analyzer trước và sau — thấy unused code → check sideEffects field và import patterns

Xem toàn bộ Build Tools cùng filter theo level & chủ đề con.

Mở danh sách Build Tools