Full answer
A single bundle makes every visitor download and parse the code of every page. Code splitting cuts the download for the first view, which helps LCP and INP, since less JavaScript must be compiled and run.
Ways to split:
- Route-based. Each page is its own chunk, loaded on navigation. Most frameworks offer this with a lazy route helper, such as
React.lazywithSuspenseor a framework's built-in routing. - Component-based. Load a heavy widget only when it opens: a rich text editor, a map, a chart, a PDF viewer.
- Vendor or shared chunks. Split code that many pages share, so it is cached once. Hashed names keep the cache valid between releases.
The tool for it is import(). Unlike a static import, it can be called anywhere, takes a string and returns a promise for the module. The bundler sees the call, creates a chunk and loads it by URL at run time.
Trade-offs to mention:
- Too many small chunks make a waterfall of requests. A chunk that is needed on every route should not be lazy.
- The first interaction with a lazy feature waits for the download. Reduce the wait with a prefetch on hover, on idle time or with
<link rel="modulepreload">. - Show a loading state and an error state. A chunk request can fail on a bad network or after a deploy removed the old file.
- A failed import after a deploy is a classic bug. Keep old chunks for a while, and reload the page when an import fails with a version mismatch.
The script uses esbuild with splitting turned on. main.js calls import('./report.js') inside a function. The result is two output files, and the code of the heavy module is only in the second one.
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = mkdtempSync(join(tmpdir(), 'split-'));
writeFileSync(join(dir, 'report.js'), "export const render = () => 'HEAVY_REPORT_CODE';\n");
writeFileSync(join(dir, 'main.js'),
"export async function openReport() { const m = await import('./report.js'); return m.render(); }\n");
const result = await build({
entryPoints: [join(dir, 'main.js')], bundle: true, splitting: true,
format: 'esm', outdir: join(dir, 'out'), write: false,
});
const files = result.outputFiles.map((f) => ({ name: f.path.split('/').pop(), text: f.text }));
console.log('output files:', files.length);
console.log('entry has heavy code:', files.find((f) => f.name === 'main.js').text.includes('HEAVY_REPORT_CODE'));
console.log('a lazy chunk has heavy code:', files.some((f) => f.name !== 'main.js' && f.text.includes('HEAVY_REPORT_CODE')));Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. The chunks were not loaded in a browser, so prefetching and failure handling were not run.
Key points
- Split by route, by heavy component and by shared vendor code.
- Dynamic import() returns a promise and creates a separate chunk.
- Too many chunks create request waterfalls.
- Prefetch likely chunks and handle loading and failure states.
- A deploy can remove old chunks. Plan for failed imports.
Common mistakes
- Lazy loading code that every page needs.
- No loading state or error handling for the dynamic import.
- Importing the heavy module statically elsewhere, which pulls it back into the main bundle.
- Deleting old hashed chunks right after a deploy.
Follow-ups
- How do you prefetch a chunk without running it?
- Why does a static import elsewhere defeat the split?
- What happens when a chunk fails to load?
Tips
- Explain the mechanism (import returns a promise) and the three ways to split.
- Name the waterfall risk to show balance.