← Back to Frontend, page 3

frontend-0044 · Medium mid

How does tree shaking work, and what stops it from removing code you do not use?

Tree shaking removes exports that nothing imports. It relies on the static shape of ES module import and export statements, so CommonJS modules cannot be shaken well, and code with side effects at the top level is kept unless the package says it has none with the sideEffects field.

Full answer

Tree shaking is dead code elimination across modules. The bundler builds the graph, marks which exports are used, and drops the rest.

It works because ES module import and export are static: they are at the top level and use string literals. The tool can read them without running the code. CommonJS require is a function call, so the target can be computed at run time, and module.exports can be changed at any time. A bundler usually has to keep the whole module.

What blocks tree shaking:

  • CommonJS or UMD packages, or code compiled to CommonJS by a tool before bundling.
  • Top-level code with side effects, such as calling a function, changing a global or patching a prototype. The bundler cannot tell if removing it is safe.
  • Barrel files that re-export everything, when the package or the bundler cannot see that the re-exports are pure.
  • Classes with static initialisers and decorators, in some setups.
  • Dynamic access such as import * as all followed by all[name].

Helpers:

  • Publish and import ES module builds. Packages can offer them through the module or exports fields.
  • The sideEffects field in package.json. "sideEffects": false tells the bundler that a file is safe to drop when its exports are unused. List the files that really have effects, such as a CSS import or a polyfill.
  • Pure annotations such as /* @__PURE__ */ on a call mark it as removable if its result is unused.
  • Import named exports directly, from specific paths when needed.

Measure with a bundle analyser. Do not assume that shaking worked.

The script below builds four small cases with esbuild. An unused ES module export disappears. An unused CommonJS export stays. A module with a top-level console.log keeps the log call, unless sideEffects is false, and then the whole file is removed. The behaviour of other bundlers can differ in details.

javascript
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

async function bundle(files, pkg) {
  const dir = mkdtempSync(join(tmpdir(), 'shake-'));
  for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text);
  if (pkg) writeFileSync(join(dir, 'package.json'), JSON.stringify(pkg));
  const r = await build({ entryPoints: [join(dir, 'main.js')], bundle: true, write: false, format: 'iife' });
  return r.outputFiles[0].text;
}

const esm = await bundle({
  'main.js': "import { used } from './lib.js'; console.log(used);",
  'lib.js': "export const used = 1; export const UNUSED_ESM = 'x';",
});
const cjs = await bundle({
  'main.js': "const { used } = require('./lib.js'); console.log(used);",
  'lib.js': "exports.used = 1; exports.UNUSED_CJS = 'x';",
});
const lib = { 'main.js': "import { unused } from './lib.js';", 'lib.js': "export const unused = 1; console.log('lib loaded');" };
const noFlag = await bundle(lib);
const withFlag = await bundle(lib, { sideEffects: false });

console.log('unused ESM export removed:', !esm.includes('UNUSED_ESM'));
console.log('unused CommonJS export removed:', !cjs.includes('UNUSED_CJS'));
console.log('side effect kept without flag:', noFlag.includes('lib loaded'));
console.log('side effect kept with sideEffects false:', withFlag.includes('lib loaded'));

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. Other bundlers can treat these cases differently, and only esbuild was run.

Key points

  • Tree shaking removes unused exports using static import and export statements.
  • CommonJS is dynamic, so it usually cannot be shaken.
  • Top-level side effects are kept unless the package declares sideEffects false.
  • Pure annotations and named imports help the tool.
  • Check the result with a bundle analyser.

Common mistakes

  • Importing a whole library with a default or namespace import when one function is needed.
  • Setting sideEffects false on a package whose files patch globals or import CSS.
  • Assuming a library is shakeable because it is small in the docs.
  • Compiling to CommonJS before the bundler sees the code.

Follow-ups

  • What does /* @__PURE__ */ tell the bundler?
  • Why are barrel files a common cause of large bundles?
  • How do you find which import added the most bytes?

Tips

  • Start from why ES modules are shakeable, then list the blockers.
  • Mention sideEffects as the knob that library authors control.