Course contentsShow
← Web Development
Lesson 1416 of 2,98225. Build Tools and BundlersFree lesson

How Tree Shaking Works

Learning the role of ES modules and static analysis in dead code elimination.

How Tree Shaking Works

You'll learn: How bundlers use ES modules and static analysis to automatically remove unused code from your final bundle.

Tree shaking sounds like magic, but it relies on a specific architectural feature: ES modules are statically analyzable. Unlike older module systems (CommonJS), ES module imports and exports are fixed at compile time—they can't be conditional or dynamic in the traditional sense.

Static Analysis: Reading Your Code Without Running It

When your bundler processes your code, it scans every ES module's import and export statements before executing anything. It builds a dependency graph showing exactly which exports are imported and used throughout your application.

Think of it like a librarian going through checkout records: they can see which books were borrowed and which sat on the shelf untouched all year. The unused books can be removed without affecting anyone.

Why ES Modules Enable This

// ES modules: static structure
import { add, subtract } from './math.js';
// Bundler knows AT BUILD TIME only 'add' and 'subtract' are needed

// CommonJS: dynamic, can't analyze
const math = require('./math.js');
// Bundler can't predict which properties you'll access

The bundler examines your imports and traces them through the entire codebase. If a function is exported but never imported anywhere, it's marked as "dead code." During the production build, these unused exports are simply excluded from the final bundle.

The Requirements

Tree shaking only works when:

  • You're using ES module syntax (import/export)
  • Your bundler is in production mode
  • Code has no side effects (or is marked as side-effect-free)

Key Takeaway: Tree shaking works because ES modules have a static structure that bundlers can analyze at build time, allowing them to trace which exports are actually used and eliminate the rest without running any code.