← Lessons

quiz vs the machine

Gold1440

Frontend

Tree Shaking and Dead Code Elimination

Bundlers drop code that no module actually imports, shrinking what ships to users.

5 min read · core · beat Gold to climb

Removing what is never used

Tree shaking is the bundler removing exports that nobody imports. It relies on the static structure of ES modules to trace which bindings are reachable from your entry points, then leaves the rest out of the final bundle.

  • The bundler builds a graph from imports and exports.
  • Unreachable exports are marked unused.
  • Minifiers then delete the dead code.

What breaks it

Tree shaking only works when the bundler can prove a piece is unused. Side effects and dynamic patterns block that proof.

  • A module with side effects at import time cannot be safely removed.
  • The sideEffects field in package json tells the bundler what is safe to drop.
  • CommonJS and require with computed names defeat static analysis.

Writing small, focused exports and avoiding top level side effects gives the bundler the most room to shrink output. Dead code elimination then strips unreferenced branches inside the kept modules, so the two techniques work together to trim the payload users download.

Key idea

Tree shaking uses static ESM imports to drop unused exports, but only when modules are free of unprovable side effects.

Check yourself

Answer to earn rating on the learn ladder.

1. What does tree shaking remove?

2. Why can side effects block tree shaking?

3. What makes tree shaking possible at all?