Tree shaking is dead-code elimination done by bundlers and minifiers (esbuild, Rollup, webpack with Terser), not by the language. ECMAScript contributes syntax a tool can analyse without running it: import and export declarations only appear at the top level of a module, and their specifiers are string literals. So the tool can build the import graph statically, mark which exports the entry point actually reaches, and leave out the rest.
Removal is conservative: top-level code that might have a side effect stays. Calls, property reads (a getter could run) and global writes are kept even when their result is unused. Two hints relax that:
/*#__PURE__*/(or/* @__PURE__ */) before a call ornew: "this call can be removed if its result is unused." It promises nothing about the function being pure in the functional sense, and it covers only the call, not side effects in its arguments."sideEffects"in a package'spackage.json: a webpack convention, also honoured by esbuild, saying which files have side effects. Withfalse, a module whose exports are all unused can be skipped entirely, including its top-level code. Rollup's core doesn't read this field;@rollup/plugin-node-resolvepasses it on.
What defeats tree shaking:
- CommonJS.
requireis an ordinary call that can take a computed path anywhere, andmodule.exportsis a mutable object read and written by computed keys. esbuild doesn't shake CommonJS at all; webpack 5 recognises a few static patterns (exports.x = …,require('a').x) and bails out on anything else. - Compiling ESM to CommonJS too early, e.g. a Babel config that transforms modules before bundling.
- Exporting one big object (
export default { a, b, c }): the object is used, so all of it stays. - Top-level side effects in libraries, such as patching prototypes on import.