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

Common Tree Shaking Pitfalls

Recognizing patterns that prevent tree shaking like barrel exports, namespace imports, and implicit side effects.

Common Tree Shaking Pitfalls

You'll learn to identify code patterns that silently sabotage tree shaking, leaving dead code in your production bundles.

The Hidden Traps

Even with proper module syntax and bundler configuration, certain coding patterns prevent tree shaking from working. These pitfalls aren't errors—they're valid JavaScript that bundlers simply can't safely optimize away.

Barrel Exports (Re-exports)

The most common culprit is the barrel file pattern:

// utils/index.js (barrel file)
export * from './math.js';
export * from './string.js';
export * from './date.js';

// Your code
import { add } from './utils';

This forces bundlers to include all exports from all files because export * creates dependencies the bundler can't untangle. Even if you only use add, everything gets bundled.

Namespace Imports

Importing entire modules as namespaces prevents tree shaking:

import * as utils from './utils.js';
utils.add(1, 2);

The bundler sees you've captured the entire module object, so it must include everything—even functions you never call.

Implicit Side Effects

Code that looks pure but isn't can block tree shaking:

export class Logger {
  constructor() {
    window.loggingEnabled = true; // Side effect!
  }
}

If your module might mutate global state, the bundler keeps it even if it's never instantiated. Without explicit "sideEffects": false declarations, bundlers err on the side of caution.

The Solution Pattern

Use direct, named imports from specific files, avoid barrel exports, and mark side-effect-free packages explicitly in your package.json.

Key Takeaway: Tree shaking fails silently with barrel exports, namespace imports, and implicit side effects—prefer direct named imports and explicit side-effect declarations to maximize dead code elimination.