Tree shaking
In short: Tree shaking removes code that is never used when building a web application. The delivered JavaScript gets smaller and loads faster.
In more detail: The bundler analyzes the import and export statements (ES modules) and detects which functions are actually used. Everything else counts as a “dead branch” and is not included in the bundle.
In Depth
- Requirement: ES modules (
import/export), notrequire(), because only they can be analyzed statically. - Side effects: Code that does something on import (for example setting globals) must not be removed. With
"sideEffects": falseinpackage.jsona library declares that it is free of them. - Practice: Import only what you need from a large library (
import { debounce } from "lib"). - Checking: A bundle analyzer shows which packages take how much space.
- Limits: Dynamically built accesses (
lib[name]) cannot be predicted by any bundler.
See also: Lighthouse and Core Web Vitals