Tree shaking is dead code elimination for JavaScript modules. The name comes from the metaphor of shaking a tree — the healthy fruit (used code) stays attached, while the dead fruit (unused code) falls to the ground.
If you have ever imported a single utility from lodash and wondered why your bundle ballooned by 70 KB, you have felt the absence of tree shaking. If you have ever switched to lodash-es and watched your bundle shrink by 60 KB, you have felt its presence.
Tree shaking is not a runtime optimization — it is a build-time one. Your bundler (webpack, Rollup, esbuild, or Vite) walks the import/export graph of your code, marks every exported symbol as "used" or "unused," and omits the unused ones from the final output. The result: smaller bundles, faster downloads, and less JavaScript for the browser to parse.
But here is the catch: tree shaking only works reliably with ES Modules (ESM). CommonJS modules cannot be tree-shaken in practice — and even with ESM, common patterns like barrel exports and unmarked side effects silently defeat the optimization.
A brief history
Tree shaking did not exist when frontend development relied on global script tags and concatenated files. It became possible when bundlers understood module boundaries — and it became powerful when ES Modules introduced a static, analyzable module grammar.
Every JS file pollutes the global scope. No import/export system. Bundlers just concatenated files in order.
require() is a function call — dynamic, runtime-resolved. Bundlers can approximate static analysis but cannot reliably eliminate dead code.
Asynchronous Module Definition for browsers. Still dynamic. define() callbacks could conditionally require dependencies.
CommonJS-in-browser era. Bundlers wrap modules in functions. Tree shaking is impossible — every module is potentially dynamic.
import/export are part of the language grammar, not a runtime API. Static analysis becomes possible because imports are immutable bindings, not function calls.
Rich Harris's Rollup was the first bundler designed around ESM. It proved that tree shaking could eliminate 90%+ of dead code in practice.
Webpack added tree-shaking support. The sideEffects flag in package.json became the standard way to tell bundlers 'this module is safe to shake.'
Vite uses Rollup for production builds (with full tree shaking) and esbuild for dev. Modern frameworks assume tree shaking by default.
import and export are syntactically baked into the language — not function calls. A bundler can parse your code, build a static module graph, and determine exactly which symbols are reachable without executing anything.