Nâng CaoBuild Tools iconBuild Tools

Tree shaking là gì? Điều kiện để tree shaking hoạt động?

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.

Pitfall: 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'.

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

Mở danh sách Build Tools