Back to results for “Bundlers & Transpilation (npm”
JavaScript › ES Modules

What is tree-shaking and why does it require ES Module syntax?

Intermediate

Answer

Tree-shaking is a bundler optimization that removes unused exports from the final bundle. It relies on ES Modules' static, analyzable import/export structure — bundlers can determine at build time exactly what's used, which isn't reliably possible with CommonJS's dynamic require() calls.
// Only 'add' gets bundled if 'subtract' is never imported anywhere
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
Real-world example Shipping a smaller JS bundle by importing only the specific lodash functions used, instead of the whole library.

Common follow-ups: Why can side effects in a module prevent tree-shaking from working correctly?