Glossary / Tree shaking
Tree shaking
Tree shaking is a build-time optimization that removes code a bundler determines is unreachable from application entry points. It works best with static ESM imports/exports, analyzable control flow, and accurate side-effect information; it is not a runtime feature and cannot generally prove arbitrary dynamic behavior irrelevant.
How it works
A bundler constructs a module graph, traces used exports, marks statements or modules as included or removable, then emits reachable code. It may combine this with dead-code elimination and minification. Static named imports expose usage; computed namespace access, CommonJS patterns, dynamic loading, reflection, or import-time effects can limit precision.
import { formatDate } from './date-utils.js';
// A bundler may omit other unused exports if it can prove they are unused.
Unused-export removal differs from module removal: evaluating a module may register handlers or mutate globals. Bundlers should preserve known effects. Incorrect package metadata claiming a package is side-effect-free can remove required initialization and break production.
Package design and validation
Libraries can improve analyzability with ESM output, narrow entry points, and explicit effect boundaries. Avoid importing broad barrels when they force unwanted evaluation, though modern bundlers often prune unused named exports. Keep package effect metadata truthful, including CSS or polyfills.
Measure emitted bundles and inspect analyzer output; source imports do not prove final output. Test production builds, optional features, and registration side effects. Dynamic imports define potential chunk boundaries, but do not guarantee optimal pruning.
Interview questions
- What enables tree shaking? Static dependency graphs and analyzable exports/effects, commonly from ESM.
- Can a bundler remove an unused module with effects? It should preserve known effects unless metadata incorrectly tells it otherwise.
- Is minification the same thing? No; minification rewrites/compresses code, tree shaking removes unreachable code.
- Why can CommonJS inhibit optimization? Runtime export mutation and dynamic loading complicate static analysis.
- How verify it worked? Inspect production output and bundle analysis, then test needed features.