SyntaxStudy
Sign Up
JavaScript Tree Shaking and Dead Code Elimination
JavaScript Intermediate 5 min read

Tree Shaking and Dead Code Elimination

Tree Shaking

Tree shaking removes unused exports from production bundles. It works with ES modules because import/export are static — bundlers can analyze them at build time.

Example
// utils.js — 3 exports
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
export function multiply(a, b) { return a * b; }

// app.js — only uses add
import { add } from "./utils.js";
console.log(add(2, 3));

// After tree shaking, bundle contains only add()
// subtract() and multiply() are eliminated
Pro Tip

Avoid side effects in module-level code — they prevent tree shaking because bundlers must keep the entire module.