Full answer
Browsers can load ES modules, but a real application can have hundreds of modules and dependencies. A bundler (webpack, Rollup, esbuild, Vite and Parcel use these or similar tools) builds the dependency graph starting from entry files, then outputs optimized bundles. It also handles other things: transforming TypeScript and JSX, minifying, processing CSS and assets, code splitting (separate files loaded on demand through import()), content hashes for caching, and development servers with hot reload.
Tree shaking is dead code elimination across modules: the bundler marks which exports are used and drops the rest. It works because ES module import and export are static. They cannot be conditional and their names are known at build time, so the tool can analyze them without running code. CommonJS require is dynamic (it can be called in an if with a computed path), so tools usually have to keep the whole module.
What blocks tree shaking:
- CommonJS modules, or a library that publishes only CommonJS.
- Side effects at module level. A top-level call like
registerPlugin()or a patch of a global must run when the module loads, so the bundler cannot remove the module without changing behavior. Pure marked calls (/* @__PURE__ */) tell the tool that a call can be removed if its result is unused. - Barrel files (
index.jsthat re-exports everything) combined with a package that is not marked side-effect free. - Classes with static properties and other constructs that the tool cannot prove are pure.
Controls: the sideEffects field in package.json can be false (no module in the package has side effects, so unused modules can be dropped) or a list of files that do have them (such as CSS files). Write libraries as ES modules, export many small functions instead of one big object, and import only what you need (import { debounce } from 'lib').
Measure rather than guess: check the output size, use a bundle analyzer, and compare the result of production mode builds, because tree shaking and minification often only run there. The snippet bundles virtual modules with esbuild, in memory, to show the effect.
const esbuild = require('esbuild');
const files = {
'entry-esm.js': `import { used } from './lib-esm.js'; console.log(used());`,
'lib-esm.js': `
export function used() { return 'used function'; }
export function unusedOne() { return 'UNUSED_MARKER_ONE'; }
export const unusedTwo = ['CALL_MARKER'].map((text) => text + '!');
export const unusedThree = /* @__PURE__ */ ['PURE_MARKER'].map((text) => text + '!');
`,
'entry-cjs.js': `const lib = require('./lib-cjs.js'); console.log(lib.used());`,
'lib-cjs.js': `
exports.used = function () { return 'used function'; };
exports.unusedOne = function () { return 'UNUSED_MARKER_ONE'; };
`,
'entry-effect.js': `import { used } from './lib-effect.js'; console.log(used());`,
'lib-effect.js': `
globalThis.registered = 'SIDE_EFFECT_MARKER';
export function used() { return 'used function'; }
export function unusedOne() { return 'UNUSED_MARKER_ONE'; }
`,
};
const virtual = {
name: 'virtual-files',
setup(build) {
build.onResolve({ filter: /.*/ }, (args) => ({ path: args.path.replace('./', ''), namespace: 'virtual' }));
build.onLoad({ filter: /.*/, namespace: 'virtual' }, (args) => ({ contents: files[args.path], loader: 'js' }));
},
};
async function bundle(entry) {
const result = await esbuild.build({
entryPoints: [entry],
bundle: true,
write: false,
format: 'esm',
plugins: [virtual],
logLevel: 'silent',
});
return result.outputFiles[0].text;
}
async function main() {
const esm = await bundle('entry-esm.js');
console.log('ESM bundle keeps the used function:', esm.includes('used function'));
console.log('ESM bundle drops unusedOne:', !esm.includes('UNUSED_MARKER_ONE'));
console.log('unused export with a plain call is kept:', esm.includes('CALL_MARKER'));
console.log('unused export marked as pure is dropped:', !esm.includes('PURE_MARKER'));
const cjs = await bundle('entry-cjs.js');
console.log('CommonJS bundle still contains unusedOne:', cjs.includes('UNUSED_MARKER_ONE'));
const effect = await bundle('entry-effect.js');
console.log('module with a side effect keeps the global assignment:', effect.includes('SIDE_EFFECT_MARKER'));
console.log('and still drops unusedOne:', !effect.includes('UNUSED_MARKER_ONE'));
console.log('esbuild version:', esbuild.version);
}
main();Run with Node.js v24.22.1 as js-137.js; two runs gave identical output. Output: ESM bundle keeps the used function: true ESM bundle drops unusedOne: true unused export with a plain call is kept: true unused export marked as pure is dropped: true CommonJS bundle still contains unusedOne: true module with a side effect keeps the global assignment: true and still drops unusedOne: true esbuild version: 0.28.2
Key points
- A bundler builds a module graph, combines, transforms, minifies, and splits code.
- Tree shaking removes unused exports using the static structure of ES modules.
- CommonJS, top-level side effects, and impure initialization block it.
- Use the sideEffects field, pure annotations, ES module output, and small exports.
- Measure with the production build and a bundle analyzer.
Common mistakes
- Publishing a library only as CommonJS and then expecting tree shaking.
- Putting side effects at the top level of modules in a library.
- Importing a whole library when only one function is needed.
- Judging bundle size from a development build.
Follow-ups
- What is the difference between tree shaking and code splitting?
- What does the sideEffects field in package.json mean?
- Why are barrel files sometimes a problem for bundle size?
Tips
- Explain that ES module imports are static, and so analyzable.
- Name what blocks tree shaking: CommonJS and side effects.
- Mention measuring with the production build and an analyzer.