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

CommonJS and Tree Shaking Limitations

Understanding why CommonJS modules cannot be tree-shaken and the importance of ESM-first packages.

CommonJS and Tree Shaking Limitations

You'll learn why CommonJS modules cannot be effectively tree-shaken and why modern packages should prioritize ESM.

The Core Problem

Tree shaking relies on static analysis—the bundler needs to determine at build time which exports are used and which aren't. This requires examining your code without executing it.

CommonJS (require() and module.exports) makes this nearly impossible because it's dynamic by nature. You can conditionally require modules, compute module paths at runtime, or dynamically build exports. The bundler can't predict what will happen until the code actually runs.

// CommonJS - bundler can't analyze this statically
const moduleName = condition ? './moduleA' : './moduleB';
const myModule = require(moduleName); // Which module? Unknown at build time!

module.exports.something = condition ? funcA : funcB; // Which export? Unknown!

Why ESM Enables Tree Shaking

ES modules (import/export) require static structure: all imports and exports must be declared at the top level with literal strings. No conditionals, no computed paths, no runtime decisions.

// ESM - bundler knows exactly what's imported
import { usedFunction } from './module'; // Clear, static dependency

The Package Ecosystem Impact

Modern libraries publish ESM-first (or ESM-only) because:

  • Bundlers can tree-shake unused exports, reducing bundle size
  • Developers get faster builds and smaller production bundles
  • The JavaScript ecosystem moves toward standardization

If a library only provides CommonJS, every import pulls in the entire module—you lose all tree shaking benefits, even if you only use one function from a large library.

Key Takeaway: CommonJS's dynamic nature prevents static analysis, making tree shaking impossible. Always prefer ESM (import/export) for modern JavaScript projects to enable dead code elimination.