Tree shaking là dead code elimination — loại bỏ unused exports khỏi bundle dựa trên static analysis của import/export statements.
- Mechanism: bundler build dependency graph, mark exports nào được imported ở đâu, eliminate exports không được referenced — chỉ possible với ES modules (static structure) vì CommonJS require() là dynamic (runtime).
- Điều kiện để tree shaking hoạt động: phải dùng ES modules (import/export không phải require/module.exports); modules phải side-effect free — library phải khai báo sideEffects: false trong package.json (nếu không Webpack giữ lại toàn bộ module vì không chắc chắn); không có dynamic imports của cùng module. sideEffects field: sideEffects: false nói với bundler 'không có file nào trong package này có side effects khi import' — safe to tree shake; sideEffects: ['.css', './src/setup.js'] exclude specific files. /#__PURE__/ annotation: đánh dấu function call không có side effects — bundler có thể eliminate nếu result không được used: const result = /#__PURE__*/ createComponent() — phổ biến trong React compiled output.
- Lưu ý: nhiều utility libraries vẫn dùng CommonJS (lodash) — không tree-shakeable; dùng lodash-es (ESM version) hoặc import từ specific path: import debounce from 'lodash/debounce'.
- Named exports tree-shake tốt hơn default exports vì bundler biết chính xác tên được dùng.
Tree shaking is dead-code elimination — removing unused exports from the bundle based on static analysis of import/export statements.
- Mechanism: the bundler builds a dependency graph, marks which exports are imported and where, and eliminates exports that are never referenced — this is only possible with ES modules (static structure) because CommonJS require() is dynamic (runtime).
- Conditions for tree shaking to work: must use ES modules (import/export, not require/module.exports); modules must be side-effect free — libraries must declare sideEffects: false in package.json (otherwise Webpack keeps the entire module because it cannot be certain); no dynamic imports of the same module.
- The sideEffects field: sideEffects: false tells the bundler "no file in this package has side effects when imported" — safe to tree shake; sideEffects: ['*.css', './src/setup.js'] excludes specific files.
- The /#__PURE__/ annotation: marks a function call as having no side effects — the bundler can eliminate it if the result is unused: const result = /#__PURE__/ createComponent() — common in compiled React output.
Pitfall: many utility libraries still use CommonJS (lodash) — not tree-shakeable; use lodash-es (ESM version) or import from a specific path: import debounce from 'lodash/debounce'.