TExcelTAD

Toolkit: Inspecting Bundles

"The bundle got 400 KB bigger" is a question about the module graph, and every bundler can answer it if you ask for the data. This lesson collects the tools: what each bundler reports, how to measure the size that matters, how to enforce a budget in CI, and how to read a source map.

Question Tool
Which modules make up this bundle? esbuild --analyze / metafile, webpack --json stats, Rollup generateBundle / rollup-plugin-visualizer
Why is this module included? esbuild metafile imports, webpack stats reasons, esbuild's analyzer website
How big is it over the network? gzip/brotli size, not file size
Did this pull request make it bigger? a size budget check in CI (size-limit, bundlesize, or a script)
Which source line is this minified error in? the source map

Measure what users download

Minified size is a proxy; the browser downloads compressed bytes. Node's zlib measures both:

bash · try it yourself
mkdir -p size/src && cd size
npm init -y > /dev/null && npm pkg set type=module
npm install react@19.3.1 react-dom@19.3.1 > /dev/null && npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/index.js <<'JS'
import { createElement as h } from 'react';
import { createRoot } from 'react-dom/client';
createRoot(document.getElementById('root')).render(h('h1', null, 'hi'));
JS
npx esbuild src/index.js --bundle --minify --define:process.env.NODE_ENV='"production"' --outfile=dist/app.js --metafile=meta.json --log-level=warning
cat > size.mjs <<'JS'
import { readFileSync } from 'node:fs';
import { gzipSync, brotliCompressSync } from 'node:zlib';
const buf = readFileSync(process.argv[2]);
const kb = (n) => (n / 1024).toFixed(1) + ' KiB';
console.log(`raw ${kb(buf.length)} | gzip ${kb(gzipSync(buf, { level: 9 }).length)} | brotli ${kb(brotliCompressSync(buf).length)}`);
JS
node size.mjs dist/app.js
echo "--- biggest inputs"
jq -r '.outputs["dist/app.js"].inputs | to_entries | sort_by(-.value.bytesInOutput) | .[:4][] | "\(.value.bytesInOutput)\t\(.key)"' meta.json
raw 217.5 KiB | gzip 67.3 KiB | brotli 58.0 KiB
--- biggest inputs
204969	node_modules/react-dom/cjs/react-dom-client.production.js
7942	node_modules/react/cjs/react.production.js
3666	node_modules/react-dom/cjs/react-dom.production.js
3638	node_modules/scheduler/cjs/scheduler.production.js

Two lessons hide in these numbers: compression shrinks typical JavaScript by about two thirds, so budgets should be set on compressed size; and almost everything here is react-dom. Without --define:process.env.NODE_ENV='"production"', React's development build would be bundled, several times larger.

A size budget in CI

The same measurement, turned into a check that fails a pull request:

bash · try it yourself
mkdir -p budget/src && cd budget
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
cat > check-size.mjs <<'JS'
import { readFileSync } from 'node:fs';
import { gzipSync } from 'node:zlib';
const [file, limitKiB] = process.argv.slice(2);
const gz = gzipSync(readFileSync(file), { level: 9 }).length / 1024;
const ok = gz <= Number(limitKiB);
console.log(`${file}: ${gz.toFixed(1)} KiB gzip (budget ${limitKiB} KiB) ${ok ? 'OK' : 'OVER BUDGET'}`);
process.exit(ok ? 0 : 1);
JS
echo 'import chunk from "lodash/chunk.js"; console.log(chunk([1, 2, 3], 2));' > src/index.js
npx esbuild src/index.js --bundle --minify --outfile=dist/app.js --log-level=warning
node check-size.mjs dist/app.js 5; echo "exit $?"
echo "--- someone switches to a named import from lodash"
echo 'import { chunk } from "lodash"; console.log(chunk([1, 2, 3], 2));' > src/index.js
npx esbuild src/index.js --bundle --minify --outfile=dist/app.js --log-level=warning
node check-size.mjs dist/app.js 5; echo "exit $?"
dist/app.js: 1.9 KiB gzip (budget 5 KiB) OK
exit 0
--- someone switches to a named import from lodash
dist/app.js: 26.2 KiB gzip (budget 5 KiB) OVER BUDGET
exit 1

A one-line import change grew the bundle by an order of magnitude; the budget caught it. Tools like size-limit do the same with nicer reports and can comment on pull requests.

Webpack's stats

webpack --json writes everything Webpack knows about the build: every module, chunk, asset and the reasons each module was included. jq turns it into answers:

bash · try it yourself
mkdir -p wps/src && cd wps
npm init -y > /dev/null && npm pkg set type=module
npm install chalk@6.0.1 > /dev/null && npm install -D webpack@5.112.2 webpack-cli@7.2.3 > /dev/null 2>&1
echo 'export const fmt = (s) => s.toUpperCase();' > src/fmt.js
echo 'import chalk from "chalk"; import { fmt } from "./fmt.js"; console.log(chalk.green(fmt("ok")));' > src/index.js
npx webpack --mode production --entry ./src/index.js --target node --json > stats.json 2> /dev/null
jq -r '.assets[] | "\(.name)  \(.size) bytes"' stats.json
jq -r '[.modules[] | (.modules // [.])[]] | unique_by(.name) | sort_by(-.size) | .[:4][] | "\(.size)\t\(.name)"' stats.json
jq -r '[.modules[] | (.modules // [.])[] | select(.name == "./src/fmt.js")][0].reasons[] | "\(.moduleName) -> \(.userRequest) (\(.type))"' stats.json
main.js  8022 bytes
8334	./node_modules/chalk/source/index.js
6996	./node_modules/chalk/source/vendor/ansi-styles/index.js
4465	./node_modules/chalk/source/vendor/supports-color/index.js
1187	./node_modules/chalk/source/utilities.js
./src/index.js -> ./fmt.js (harmony side effect evaluation)
./src/index.js -> ./fmt.js (harmony import specifier)

The stats file is also what visual tools read: webpack-bundle-analyzer draws it as a treemap, and the online analyzers for esbuild metafiles and webpack stats do the same in the browser.

Reading a source map

A production error says app.js:1:64: line 1 (minified code is one line), column 64. The source map translates that back to the original file and line. The source-map library (the one bundlers use) does the lookup:

bash · try it yourself
mkdir -p sm/src && cd sm
npm init -y > /dev/null && npm pkg set type=module
npm install -D esbuild@0.28.2 source-map@0.6.1 > /dev/null 2>&1
cat > src/cart.js <<'JS'
export function total(items) {
  return items.reduce((sum, item) => {
    if (item.price < 0) throw new Error(`negative price for ${item.name}`);
    return sum + item.price;
  }, 0);
}
JS
echo 'import { total } from "./cart.js"; console.log(total([{ name: "pen", price: 2 }, { name: "bad", price: -1 }]));' > src/index.js
npx esbuild src/index.js --bundle --minify --sourcemap --outfile=dist/app.js --log-level=warning
node dist/app.js 2>&1 | grep -o 'app.js:[0-9]*:[0-9]*' | head -1
node --enable-source-maps dist/app.js 2>&1 | grep -m1 -o 'src/cart.js:[0-9]*:[0-9]*'
cat > lookup.cjs <<'JS'
const { SourceMapConsumer } = require('source-map');
const fs = require('fs');
const [line, column] = process.argv.slice(2).map(Number);   // from the stack trace: 1-based
const map = new SourceMapConsumer(JSON.parse(fs.readFileSync('dist/app.js.map', 'utf8')));
console.log(map.originalPositionFor({ line, column: column - 1 }));   // source-map columns are 0-based
JS
pos=$(node dist/app.js 2>&1 | grep -o 'app.js:[0-9]*:[0-9]*' | head -1 | cut -d: -f2,3 | tr ':' ' ')
node lookup.cjs $pos
app.js:1:64
src/cart.js:3:31
{ source: '../src/cart.js', line: 3, column: 30, name: null }

The minified position maps back to src/cart.js, line 3, where the throw is. node --enable-source-maps does the same translation for whole stack traces; error trackers (Sentry and friends) do it server-side with source maps you upload privately.

Test yourself

Which size should a bundle budget usually be set on?

  1. The unminified size
  2. The compressed (gzip/brotli) size users actually download
  3. The number of modules
  4. The source map size

In webpack's stats JSON, what do a module's reasons tell you?

  1. Why the build failed
  2. Which modules import it, and how
  3. Its gzip size
  4. Its license

What does node --enable-source-maps change?

  1. It generates source maps
  2. It translates stack traces through available source maps to original files and lines
  3. It minifies the code
  4. It disables source maps