Sub topic 18
Why Static Structure Enables Tree Shaking
This chapter assumes you know the import and export forms from earlier chapters and that you have run a command-line tool with npx. It also helps to know what re-exports and barrel modules are. You do not need to have used a bundler before.
A bundler is a tool that reads your modules and combines them into fewer files for shipping. Tree shaking is the bundler step that removes exports nobody imports. This chapter explains why ES modules make that removal possible, what stops it from working, and how to write code that bundlers can trim.
What "static structure" means
An ES module's imports and exports are fixed before any of its code runs. The language enforces three rules:
importandexportdeclarations may appear only at the top level of a module. They cannot sit inside anif, a function, or a loop.- The module specifier in an
importdeclaration must be a string literal. It cannot be a variable or an expression. - The names you import and export are identifiers written in the source. You cannot compute them at runtime.
Because of these rules, a tool can parse a file and list every import and export without running it. The chapter on the module lifecycle described how the engine uses this during linking. Bundlers make the same pass at build time.
Compare this with CommonJS:
// CommonJS: none of this can be known without running it
const name = process.env.USE_FAST ? './fast.cjs' : './slow.cjs';
const lib = require(name);
if (lib.ready) {
module.exports[`handler_${Date.now()}`] = lib.run;
}The require call takes a computed path. The export name is built at runtime, and the export only exists when a condition is true. A tool reading this file cannot tell which module gets loaded or what the file exports. It has to keep everything.
How a bundler shakes the tree
The bundler starts at your entry module and follows every import declaration to build a module graph: one node for each module, and one edge for each import. For each edge it records which names are used. An export that no edge asks for, and that nothing inside its own module uses, is a candidate for removal.
Here is a small project you can bundle yourself.
// strings.js
export function slugify(text) {
return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-');
}
export function capitalize(text) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
// main.js
import { slugify } from './strings.js';
console.log(slugify('Hello ES Modules'));Run esbuild with bundling turned on:
npx esbuild main.js --bundle --format=esm --outfile=out.jsOpen out.js. It contains slugify and the console.log call, but not capitalize. Nothing imported capitalize, and its declaration does nothing when it runs, so removing it cannot change what the program does.
That second condition is the important one. The bundler must prove a piece of code is both unused and free of side effects. A side effect is anything a statement does beyond producing a value, such as writing to a global, logging, or changing an object that something else can see.
What defeats tree shaking
Static syntax tells the bundler which names are imported. It does not tell the bundler what the code does when it runs. Most failures come from that gap.
Exporting one big object
// utils.js
export default {
slugify(text) { return text.toLowerCase(); },
capitalize(text) { return text[0].toUpperCase() + text.slice(1); },
};
// main.js
import utils from './utils.js';
console.log(utils.slugify('Hi'));The export is a single value. Bundlers track exports, and they do not reliably track which properties of an object you read. The whole object, both methods included, usually ends up in the bundle. Separate named exports give the bundler one unit per function.
Namespace objects used dynamically
import * as strings from './strings.js' is fine when you write strings.slugify(...), because bundlers can see the property access. If you write strings[methodName] or pass strings to another function, the bundler cannot tell which exports you need, so it keeps all of them.
Top-level side effects
// analytics.js
export function track(event) {
console.log('track', event);
}
window.analyticsLoaded = true; // side effect: runs on importEven if no one imports track, the assignment to window must stay, because removing it would change behavior. As the side-effect imports chapter showed, some modules exist only for effects like this. The bundler cannot tell an intentional effect from an accidental one.
Calls the bundler cannot prove are pure
export const theme = createTheme({ primary: 'blue' });If theme is never imported, can the createTheme call go? Only if the bundler knows the call has no side effects, and in general it does not. Many tools accept a hint comment:
export const theme = /*#__PURE__*/ createTheme({ primary: 'blue' });The comment tells esbuild, Rollup, webpack, and Terser that dropping the call is safe when its result is unused. The hint is a promise from you, and the tools do not check it.
Dynamic import() with a computed specifier
import('./locales/' + lang + '.js') cannot be resolved at build time. Bundlers either include every file that matches the pattern or leave the call for runtime. A literal specifier like import('./chart.js') is still analyzable, and bundlers usually split it into a separate chunk.
The sideEffects field and barrel modules
Barrel modules (export * from ...) make the problem bigger. Importing one name from shapes/index.js gives the bundler a reason to look at every module the barrel re-exports. If any of those modules might have side effects, the bundler has to keep them.
Package authors can declare which files are safe to skip in package.json:
{
"name": "geometry",
"version": "1.0.0",
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.js"
}
}"sideEffects": false tells webpack, Rollup, and esbuild that any module in the package can be dropped entirely when none of its exports are used. If a few files do have effects, such as CSS imports or polyfills, list them in an array instead: "sideEffects": ["./src/polyfill.js", "*.css"]. This field is a bundler convention. Node.js ignores it.
A checklist for shakeable code
| Practice | Why it helps |
|---|---|
| Prefer many named exports over one exported object | Each export is a separate unit the bundler can drop |
| Keep module top levels free of side effects | Unused modules can be removed entirely |
| Use literal specifiers, even in `import()` | The bundler can resolve and split the target |
| Access namespace imports with dot notation | Usage stays visible to static analysis |
| Mark pure factory calls with `/*#__PURE__*/` | Allows removal of unused computed exports |
| Declare `sideEffects` accurately in libraries | Lets bundlers skip whole files behind barrels |
| Ship ES module builds, not only CommonJS | `require` and `module.exports` are too dynamic to shake reliably |
Common mistakes
- Testing tree shaking in development mode. Many tools only shake code in production builds. Check the production output.
- Assuming class methods are shaken. A class is one value. If you import the class, all of its methods stay.
- Blaming the bundler for CommonJS dependencies. If a dependency only publishes CommonJS, most of it stays in the bundle no matter how you import it.
Exercise
A module exports export const formatters = { date: formatDate, money: formatMoney }; and also export function formatDate(d) {...} and export function formatMoney(n) {...}. Your app does import { formatters } from './format.js' and calls only formatters.date(now). Will formatMoney be removed from the bundle? How would you change the import to let it be removed?
Show answer
Usually not. The app imports the formatters object, and that object holds a reference to formatMoney, so the bundler has to keep both functions. Change the import to import { formatDate } from './format.js' and call formatDate(now). Then formatters and formatMoney are both unused and can be dropped, as long as their declarations have no side effects.
Exercise
A library's index.js has export * from './a.js'; export * from './b.js';. The file b.js contains globalThis.registry = new Map(); at the top level. An app imports one function from a.js through the barrel. Without a sideEffects field, what happens to b.js, and what is the correct fix?
Show answer
The bundler keeps the top-level assignment in b.js because removing it would change behavior, even though no export from b.js is used. Setting "sideEffects": false would be wrong because b.js really does have an effect. The correct fix is to list it, as in "sideEffects": ["./src/b.js"], or better, to move the registry setup into a function that callers invoke explicitly so that b.js has no top-level effects.
Exercise
Why can a bundler resolve import('./chart.js') at build time but not const lib = require(name) where name is a variable?
Show answer
The import() call uses a string literal, so the bundler can read the target path from the source without running anything. The require call's argument is a runtime value, so the target is unknown until the code runs. The bundler has to guess, include many files, or leave the call unresolved.