What Is Tree Shaking and How Does It Work
· Category: Web Performance
Short answer
Tree shaking is a form of dead code elimination that removes unused exports from JavaScript bundles. It works best with ES module syntax.
How it works
The bundler analyzes the static import/export graph. Functions and variables that are never imported are excluded from the final output. Side-effect-free modules are fully tree-shakeable.
Example
// utils.js
export function used() { /* ... */ }
export function unused() { /* ... */ }
// app.js
import { used } from './utils.js';
// unused is removed from the bundle
Why it matters
Smaller bundles parse and execute faster. Tree shaking lets you import from large utility libraries like Lodash without including the entire package.