← Lessons

quiz vs the machine

Gold1410

Frontend

The Tree Shaking

Drop unused exports from the final bundle by analyzing what code is actually imported.

4 min read · core · beat Gold to climb

Removing dead code

Tree shaking is the removal of code that is never used, so it is excluded from the final bundle. The name pictures shaking a dependency tree so the dead branches, the unused exports, fall away.

  • The bundler analyzes which exports each module actually imports.
  • Exports that no one references are marked as unused.
  • Those unused exports are dropped from the output.

What makes it possible

Tree shaking relies on static module structure, specifically ES module import and export. Because these are analyzable without running the code, the bundler can prove what is reachable.

  • ES modules are static, so imports are known at build time.
  • Older CommonJS require is dynamic and resists analysis.
  • Side effects, like code that runs on import, must be marked so they are kept.

This is why importing one function from a large library can pull in just that function rather than the whole thing, if the library is written to be tree shakeable. Done well, it can dramatically shrink bundles by deleting code you never call.

Key idea

Tree shaking analyzes static ES module imports to drop exports nobody references from the bundle, shrinking output, but it needs side effects marked and static imports to safely prove what code is unreachable.

Check yourself

Answer to earn rating on the learn ladder.

1. What does tree shaking remove?

2. Why do ES modules enable tree shaking better than CommonJS?

3. Why must side effects be marked during tree shaking?