Code Splitting & Chunks
One bundle per application is simple, but it makes every visitor download every feature before anything runs, and any change invalidates the whole file in browser caches. Code splitting cuts the module graph into several output files, called chunks:
| Split point | Why |
|---|---|
multiple entry points (admin.js, shop.js) |
each page loads only its own code; shared modules go into a shared chunk so they're downloaded once |
dynamic import() |
a module loaded on demand (a chart editor, a settings dialog) becomes its own lazy chunk |
vendor chunks (node_modules) |
libraries change less often than your code, so they stay cached longer (manual configuration) |
The chunking rule, modelled
esbuild and Rollup use the same core idea: label each module with the set of entry points that reach it. Modules with the same label go into the same chunk. A dynamic import() counts as an entry point of its own.
// Static imports between modules; dynamic imports create extra entry points.
const imports = {
'admin.js': ['format.js', 'api.js'],
'shop.js': ['format.js', 'cart.js'],
'cart.js': ['api.js'],
'format.js': [],
'api.js': [],
'report.js': ['format.js', 'charts.js'], // loaded with import('./report.js') from admin.js
'charts.js': [],
};
const entries = ['admin.js', 'shop.js', 'report.js'];
const reachedBy = {};
function walk(mod, entry) {
(reachedBy[mod] ??= new Set()).add(entry);
for (const dep of imports[mod]) if (!reachedBy[dep]?.has(entry)) walk(dep, entry);
}
for (const e of entries) walk(e, e);
const chunks = {};
for (const [mod, set] of Object.entries(reachedBy)) {
const label = [...set].sort().join('+');
(chunks[label] ??= []).push(mod);
}
for (const [label, mods] of Object.entries(chunks)) {
const kind = label.includes('+') ? 'shared chunk' : `entry chunk for ${label}`;
console.log(`${kind.padEnd(26)} ${mods.sort().join(', ')}`);
}entry chunk for admin.js admin.js
shared chunk format.js
shared chunk api.js
entry chunk for shop.js cart.js, shop.js
entry chunk for report.js charts.js, report.js
format.js is reached from all three entries and api.js from admin.js and shop.js (through cart.js): different labels, so they land in two different shared chunks; charts.js is only reachable through the lazy report.js, so it never slows down the admin page's first load. Real bundlers add rules on top (merging tiny chunks, size limits, cycles), but this labelling is the heart of it.
Splitting with esbuild
esbuild splits when you pass --splitting, which requires ES module output (--format=esm) and an output directory:
mkdir -p split/src && cd split
npm init -y > /dev/null && npm pkg set type=module
npm install -D esbuild@0.28.2 > /dev/null 2>&1
cat > src/format.js <<'JS'
export const money = (n) => `${n.toFixed(2)}`;
JS
cat > src/api.js <<'JS'
export const fetchTotals = () => [12.5, 7.25];
JS
cat > src/charts.js <<'JS'
export const bar = (values) => values.map((v) => '#'.repeat(Math.round(v))).join('\n');
JS
cat > src/report.js <<'JS'
import { money } from './format.js';
import { bar } from './charts.js';
export const report = (values) => `${bar(values)}\ntotal ${money(values.reduce((a, b) => a + b, 0))}`;
JS
cat > src/admin.js <<'JS'
import { money } from './format.js';
import { fetchTotals } from './api.js';
const totals = fetchTotals();
console.log('admin: first total', money(totals[0]));
const { report } = await import('./report.js'); // loaded on demand
console.log(report(totals));
JS
cat > src/shop.js <<'JS'
import { money } from './format.js';
import { fetchTotals } from './api.js';
console.log('shop: price', money(fetchTotals()[1]));
JS
npx esbuild src/admin.js src/shop.js --bundle --splitting --format=esm --outdir=dist --log-level=warning
ls dist
grep -H -m1 "^//" dist/chunk-*.js
echo "--- admin.js imports:"; grep -o 'from "[^"]*"\|import("[^"]*")' dist/admin.js
node dist/admin.js
node dist/shop.jsadmin.js
chunk-CCL63MQ4.js
chunk-XLSMWM72.js
report-3PBSKW3U.js
shop.js
dist/chunk-CCL63MQ4.js:// src/format.js
dist/chunk-XLSMWM72.js:// src/api.js
--- admin.js imports:
from "./chunk-XLSMWM72.js"
from "./chunk-CCL63MQ4.js"
import("./report-3PBSKW3U.js")
admin: first total $12.50
#############
#######
total $19.75
shop: price $7.25
esbuild wrote the two entry files, a lazy chunk for report.js (with charts.js inside it), and the same two shared chunks as the model: one for format.js, needed by all three entry points, and one for api.js, needed by the two pages. Each page imports both shared chunk files, and the browser downloads each once. The 8-character suffix in chunk names is a content hash: the name changes only when the content does, which makes the files safe to cache forever.
Lazy loading in the browser
await import('./report.js') compiles to a request for the chunk the first time it runs; later calls reuse the loaded module. Frameworks build on it:
// React
const ReportPage = React.lazy(() => import('./ReportPage.js'));
// Vue Router
{ path: '/report', component: () => import('./ReportPage.vue') }A few practical rules:
- Split by route or by heavy feature, not by tiny component; every chunk is a network request.
- Preload chunks you'll need soon (
<link rel="modulepreload" href="…">); Vite and Webpack can inject these. - Shared chunks need ESM or a runtime. esbuild and Rollup emit native
importstatements; Webpack adds its own small runtime that loads chunks with<script>tags orimport(), which is how it supports splitting in CommonJS-style output as well.
The Webpack production lesson shows splitChunks and vendor chunks, and the Vite course covers splitting in a Vite app.
Test yourself
What turns a module into a lazily loaded chunk?
- export default
- A dynamic import() of it
- Putting it in node_modules
- Naming it *.chunk.js
Why does esbuild require --format=esm for --splitting?
- CommonJS is slower
- Chunks load each other through native import statements
- IIFE can't contain functions
- It's a licensing rule
Why do chunk file names contain a content hash?
- For security
- So a file's name changes only when its content changes, allowing long-term caching
- To make them unique per build
- Browsers require it