Dead Code Elimination
You'll learn how bundlers automatically remove unused code to shrink your final JavaScript bundle.
What Is Dead Code Elimination?
Dead code elimination (also called "tree shaking") is the process where build tools analyze your module graph and remove exports that are never imported or used anywhere in your application. Think of it like trimming dead branches from a tree—you keep only the living, active parts that contribute to the final result.
When you import just one function from a large library, you don't want the entire library in your bundle. A smart bundler traces which exports are actually used and discards the rest.
How It Works
Bundlers rely on static analysis of ES modules. Because import and export statements are static (they can't change at runtime), tools can build a complete dependency graph before execution. They mark which exports are "reachable" from your entry point and eliminate everything else.
// math.js
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; } // unused
export function multiply(a, b) { return a * b; } // unused
// app.js
import { add } from './math.js';
console.log(add(2, 3));
After bundling with dead code elimination, only add() appears in the final output. The subtract and multiply functions are completely removed because no code path references them.
Requirements for Effective Tree Shaking
- ES modules: CommonJS (
require) is dynamic and harder to analyze - Side-effect-free code: Bundlers must be confident that removing code won't break anything
- Named exports: Default exports are harder to partially eliminate
Key Takeaway: Dead code elimination uses static analysis of ES module imports and exports to remove unused code paths, significantly reducing bundle size without manual intervention.