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:
- Methods are bundled together — A class is typically treated as a single unit
- Dynamic access is possible — Code could call methods via bracket notation or reflection
- 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.