TExcelTAD

Tree Shaking & sideEffects

Tree shaking is dead-code elimination at the module level: the bundler starts from what the entry actually uses, follows imports, and leaves out every export nobody reaches. It works because ES module imports and exports are static: import { add } from './math.js' names exactly what it needs, at parse time, without running any code. CommonJS (require, module.exports = …) is dynamic, so bundlers mostly can't shake it.

A mark-and-sweep model

js · try it yourself
// Each module: its exports, and for each export which other exports it uses.
const modules = {
  'index.js': { exports: { main: ['math.js#add', 'format.js#fmt'] } },
  'math.js': { exports: { add: [], mul: [], pow: ['math.js#mul'] } },
  'format.js': { exports: { fmt: ['math.js#add'], pad: [] } },
};

const live = new Set();
(function mark(ref) {
  if (live.has(ref)) return;
  live.add(ref);
  const [file, name] = ref.split('#');
  for (const dep of modules[file].exports[name]) mark(dep);
})('index.js#main');

for (const [file, { exports }] of Object.entries(modules)) {
  for (const name of Object.keys(exports)) {
    console.log(`${(file + '#' + name).padEnd(16)} ${live.has(file + '#' + name) ? 'kept' : 'shaken out'}`);
  }
}
index.js#main    kept
math.js#add      kept
math.js#mul      shaken out
math.js#pow      shaken out
format.js#fmt    kept
format.js#pad    shaken out

pow uses mul, but nothing uses pow, so both go. Real bundlers do this per statement, and they have to answer one more question the model ignores: does evaluating this code have side effects?

Tree shaking with esbuild

bash · try it yourself
mkdir -p ts/src && cd ts
npm init -y > /dev/null && npm pkg set type=module
npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/math.js <<'JS'
export const add = (a, b) => a + b;
export const mul = (a, b) => a * b;
export function pow(a, n) { let r = 1; for (let i = 0; i < n; i++) r = mul(r, a); return r; }
JS
cat > src/index.js <<'JS'
import { add } from './math.js';
console.log(add(2, 3));
JS
npx esbuild src/index.js --bundle --format=esm --outfile=dist/out.js --log-level=warning
cat dist/out.js
// src/math.js
var add = (a, b) => a + b;

// src/index.js
console.log(add(2, 3));

mul and pow are gone without minification: esbuild only emits code reachable from the entry.

Side effects: why "unused" isn't always removable

Importing a module runs it. If a module's top level does something (registers a polyfill, patches a prototype, logs, adds CSS), dropping it changes behaviour, even if none of its exports are used. A bundler must assume any module might have side effects, unless told otherwise:

bash · try it yourself
mkdir -p fx/vendor/widgets fx/src && cd fx
cd vendor/widgets
echo '{ "name": "widgets", "version": "1.0.0", "type": "module", "main": "index.js" }' > package.json
echo 'export { button } from "./button.js"; export { chart } from "./chart.js";' > index.js
echo 'export const button = () => "<button>";' > button.js
cat > chart.js <<'JS'
console.log('chart.js: registering a huge charting library');
export const chart = () => '<canvas>';
JS
cd ../..
npm init -y > /dev/null && npm pkg set type=module
npm install ./vendor/widgets > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
echo 'import { button } from "widgets"; console.log(button());' > src/index.js
npx esbuild src/index.js --bundle --format=esm --outfile=dist/a.js --log-level=warning
echo "== without sideEffects"; node dist/a.js; cat dist/a.js
npm pkg set sideEffects=false --json --prefix vendor/widgets
npx esbuild src/index.js --bundle --format=esm --outfile=dist/b.js --log-level=warning
echo '== with "sideEffects": false'; node dist/b.js; grep -c chart dist/b.js || true
== without sideEffects
chart.js: registering a huge charting library
<button>
// vendor/widgets/button.js
var button = () => "<button>";

// vendor/widgets/chart.js
console.log("chart.js: registering a huge charting library");

// src/index.js
console.log(button());
== with "sideEffects": false
<button>
0

Without the flag, esbuild kept chart.js's console.log (the side effect) but still dropped the unused chart function. With "sideEffects": false in the package's package.json, the author promises "importing my files does nothing by itself", and the bundler drops chart.js completely. That's what makes big component libraries cheap to import from. If only some files have side effects, list them: "sideEffects": ["./polyfill.js", "*.css"].

Warning: A wrong "sideEffects": false silently deletes CSS imports and polyfills from your users' bundles. Mark CSS files and anything that patches globals as side-effectful.

CommonJS defeats tree shaking

lodash is published as CommonJS. Import one function by name and the whole library comes along:

bash · try it yourself
mkdir -p lo/src && cd lo
npm init -y > /dev/null && npm pkg set type=module
npm install lodash@4.18.1 > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
echo 'import { chunk } from "lodash"; console.log(chunk([1, 2, 3, 4], 2));' > src/named.js
echo 'import chunk from "lodash/chunk.js"; console.log(chunk([1, 2, 3, 4], 2));' > src/deep.js
npx esbuild src/named.js --bundle --minify --format=esm --outfile=dist/named.js --log-level=warning
npx esbuild src/deep.js --bundle --minify --format=esm --outfile=dist/deep.js --log-level=warning
ls -l dist | awk 'NR > 1 { print $5, $9 }'
node dist/named.js && node dist/deep.js
4055 deep.js
73816 named.js
[ [ 1, 2 ], [ 3, 4 ] ]
[ [ 1, 2 ], [ 3, 4 ] ]

The named import pulled in all of lodash; the deep import of lodash/chunk.js only that function and its helpers. Library authors avoid this by shipping an ES module build (lodash-es exists for this reason; Rollup makes it easy, see Rollup library builds).

Helping the minifier: /*#__PURE__*/

A call at the top level (const x = createStore()) might have side effects, so it's kept even if x is unused. The /*#__PURE__*/ annotation tells esbuild, Rollup, Terser and Webpack that a call can be dropped when its result is unused; compilers like TypeScript and Babel emit it for class and JSX helpers.

bash · try it yourself
mkdir -p pure && cd pure
npm init -y > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > in.js <<'JS'
function makeTable() { return new Array(1000).fill(0); }
const kept = makeTable();
const dropped = /*#__PURE__*/ makeTable();
export const answer = 42;
JS
npx esbuild in.js --bundle --minify --format=esm --log-level=warning
function e(){return new Array(1e3).fill(0)}var n=e();var r=42;export{r as answer};

Test yourself

Why can bundlers tree-shake ES modules much better than CommonJS?

  1. ES modules are smaller
  2. import/export are static, so used exports are known at build time
  3. CommonJS can't be bundled
  4. Only ES modules can be minified

What does "sideEffects": false in a package's package.json promise?

  1. The package has no dependencies
  2. Importing any of its files without using their exports has no observable effect, so unused files can be dropped
  3. The package works without JavaScript
  4. The package is pure TypeScript

Why was import { chunk } from 'lodash' so much bigger than import chunk from 'lodash/chunk.js'?

  1. The named import is minified differently
  2. lodash's main entry is one CommonJS module containing everything, which can't be shaken
  3. esbuild doesn't support named imports
  4. chunk.js is a stub