Reference guide · performance · Published 2026-08-16 · 3 min read

How tree shaking removes dead JavaScript and why it can fail

Tree shaking and dead code elimination in JS bundlers, side-effect detection, and pitfalls that silently keep code.

Tree shaking is the removal of unused code at build time. A bundler can drop an exported function your project never imports, which shrinks the JavaScript a browser must download, parse and execute. It only works reliably with ES modules, and a few common patterns stop it dead.

How it works

A simple example (the second export is unused and can be dropped):

// utils.js
export const used = () => 42;
export const unusedHelper = () => expensiveCalculation();

// index.js
import { used } from "./utils.js";
console.log(used());

What blocks it

Enable it fully

  1. Author ES modules end to end. Keep your source and dependencies in import/export. Convert or avoid CommonJS code at the edges so the standing graph stays static.
  2. Mark sideEffects in package.json. If your package has no side effects, set "sideEffects": false. If only certain files have effects, list them: "sideEffects": ["./src/polyfills.js"].
  3. Write pure, importable code. Move side effects (global setup, analytics) into explicitly marked files so the rest can be pruned.
  4. Confirm with your bundler's profiler. Build tools such as Webpack, Rollup and esbuild report output sizes; compare a full bundle against one where you disabled tree shaking or added no side-effect hints, to confirm the tool is actually pruning.
  5. Verify per-feature. A component library that ships many components benefits most; check that importing one component yields a small chunk, not the whole library. For route-level scale this pairs with code splitting.

Prevention

Need a website built, fixed, optimised, migrated or replaced?

This technical resource is written by CSMBAC, a small design and development studio. If you would rather hand the problem to a professional, the website service page explains how we build enquiry-ready websites.

Explore website services