What is Tree Shaking?

Tree shaking is a build-time optimisation where the bundler removes exported code that is never imported or used, based on the static import/export structure of ES modules.

How it works

ES module imports and exports are static: they are at the top level and cannot change at runtime. The bundler builds a graph of which exports are actually used, marks the rest as dead, and the minifier removes them. Rollup popularised it; webpack, Vite, esbuild and Turbopack all do it.

What breaks tree shaking

  • CommonJS (require/module.exports) is dynamic, so bundlers usually cannot remove unused parts.
  • Side effects at import time: if a module runs code when imported (patching globals, registering things), the bundler must keep it. Packages declare "sideEffects": false (or a list of files) in package.json to say imports can be dropped safely.
  • Importing everything: import _ from "lodash" pulls in the whole library. Use lodash-es with named imports, or per-method imports.
  • Barrel files (index.js that re-exports everything) can slow builds and sometimes defeat tree shaking. Next.js has optimizePackageImports for popular libraries with this problem.
  • Dynamic property access on namespace imports (utils[name]).

How to check

Use a bundle analyser (@next/bundle-analyzer, rollup-plugin-visualizer, source-map-explorer) to see what ends up in each chunk.

Writing tree-shakeable libraries

Ship ES modules, avoid top-level side effects, mark them with sideEffects, and export small independent functions rather than one big object.

Code example

js
1// math.js - an ES module with several exports
2export const add = (a, b) => a + b;
3export const multiply = (a, b) => a * b;
4export function heavyStatistics(data) {
5 /* hundreds of lines nobody imports */
6}
7
8// app.js
9import { add } from "./math.js"; // only `add` ends up in the bundle
10console.log(add(2, 3));
11
12// Tree-shake friendly vs not:
13import { debounce } from "lodash-es"; // ESM, named import: only debounce is bundled
14// import _ from "lodash"; // CommonJS default import: the whole library is bundled
15
16// A side effect at import time forces the bundler to keep the module:
17// polyfills.js
18// Array.prototype.last = function () { return this[this.length - 1]; };
19
20// package.json of a library: tell bundlers which files have side effects
21// {
22// "name": "my-ui-kit",
23// "type": "module",
24// "sideEffects": ["*.css"]
25// }
26
27export { debounce };

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app