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.