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) inpackage.jsonto say imports can be dropped safely. - Importing everything:
import _ from "lodash"pulls in the whole library. Uselodash-eswith named imports, or per-method imports. - Barrel files (
index.jsthat re-exports everything) can slow builds and sometimes defeat tree shaking. Next.js hasoptimizePackageImportsfor 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
1// math.js - an ES module with several exports2export const add = (a, b) => a + b;3export const multiply = (a, b) => a * b;4export function heavyStatistics(data) {5 /* hundreds of lines nobody imports */6}78// app.js9import { add } from "./math.js"; // only `add` ends up in the bundle10console.log(add(2, 3));1112// Tree-shake friendly vs not:13import { debounce } from "lodash-es"; // ESM, named import: only debounce is bundled14// import _ from "lodash"; // CommonJS default import: the whole library is bundled1516// A side effect at import time forces the bundler to keep the module:17// polyfills.js18// Array.prototype.last = function () { return this[this.length - 1]; };1920// package.json of a library: tell bundlers which files have side effects21// {22// "name": "my-ui-kit",23// "type": "module",24// "sideEffects": ["*.css"]25// }2627export { 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.