Course contentsShow
← JavaScript
Lesson 2471 of 2,72350. JavaScript Build ToolingFree lesson

Tree Shaking Class Methods

Why unused class methods are harder to tree shake and how bundlers handle class static analysis.

Tree Shaking Class Methods

You'll learn why bundlers struggle to remove unused methods from JavaScript classes, even when they're never called.

Why Classes Resist Tree Shaking

When you export a class, bundlers have a hard time determining which methods are actually used. Unlike top-level functions that can be analyzed statically, class methods are properties attached to a prototype. The bundler must assume the entire class might be needed because:

  1. Methods are bundled together — A class is typically treated as a single unit
  2. Dynamic access is possible — Code could call methods via bracket notation or reflection
  3. Inheritance complicates analysis — Subclasses might rely on parent methods in unpredictable ways

The Problem in Practice

// math.js
export class MathUtils {
  add(a, b) { return a + b; }
  subtract(a, b) { return a - b; }
  multiply(a, b) { return a * b; }
  divide(a, b) { return a / b; }
}

// main.js
import { MathUtils } from './math.js';
const utils = new MathUtils();
console.log(utils.add(2, 3));

Even though only add() is called, bundlers typically include all four methods because they're part of the class definition. The bundler can't safely assume subtract, multiply, or divide won't be called somewhere.

What Bundlers Try to Do

Modern bundlers attempt class-level tree shaking but are conservative. They'll remove an entire unused class but rarely individual methods. Some bundlers can eliminate methods if the class is never instantiated and methods are accessed statically, but this is limited.

Key Takeaway: Class methods are harder to tree shake than standalone functions because bundlers must treat classes as cohesive units to avoid breaking dynamic behavior—prefer exporting individual functions when tree shaking is critical.