Tree shaking removes code that is never used from a JavaScript bundle, keeping only the parts that are actually imported and executed. It analyses the import/export statements in ES modules and discards the rest, so the final file that reaches the browser contains fewer bytes.
Also called: dead code elimination
Why it matters
A smaller bundle loads faster, consumes less bandwidth and reduces the time a visitor waits before they can interact with the site, which directly improves conversion rates and search rankings.
How it works
During the build, bundlers such as Webpack, Rollup or esbuild build a dependency graph of all ES module imports and exports. They then mark which exports are reachable from the entry points and prune the unused ones before writing the final bundle, often using the “sideEffects” flag in package.json to guide the process.
The mistake people make
Many developers assume tree shaking works with CommonJS modules or files that have side effects, but static analysis cannot reliably determine usage in those cases, so the unwanted code remains and the bundle stays large.