Configure Rollup Code Splitting with Dynamic Imports for Browser SPAs
Configure Rollup to split a browser SPA into an entry chunk, shared vendor bundle, and per-route lazy chunks using dynamic import(). Covers rollup.config.mjs setup, static import() boundaries, verification steps, and fixes for missing chunks or oversized vendor bundles.
07 Nov 2025, 11:06 UTC

Problem and Takeaway
Shipping a single large JavaScript bundle hurts initial load performance in single-page applications. Rollup can automatically split code into multiple chunks when you use dynamic import() expressions, producing an entry chunk, per-route lazy chunks, and a shared vendor chunk—all loadable via native <script type=module> without a custom runtime loader.
Prerequisites
- Rollup 3.x or 4.x installed (
npm i -D rollup) - Project uses ES modules (
"type": "module"inpackage.jsonor.mjsfiles) - Entry point contains dynamic
import()calls for code-split boundaries @rollup/plugin-node-resolveand@rollup/plugin-commonjsconfigured for npm dependencies
Minimal Rollup Configuration
Create rollup.config.mjs at the project root:
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/main.js',
output: {
dir: 'dist',
format: 'esm',
entryFileNames: 'entry-[hash].js',
chunkFileNames: 'chunk-[hash].js',
manualChunks: (id) => {
if (id.includes('node_modules')) return 'vendor';
},
sourcemap: true
},
plugins: [resolve(), commonjs()]
};
Key settings explained:
output.dir(notoutput.file) enables multi-chunk emissionformat: 'esm'produces standard ES modules loadable by modern browsersmanualChunksfunction forces allnode_modulescode into a singlevendorchunk[hash]in file names provides cache-busting for production deployments
Defining Split Boundaries in Application Code
In your entry module (src/main.js), use static dynamic imports for each lazy-loaded feature:
// src/main.js
import { initApp } from './app.js';
// Router example: each route loads its own chunk
async function navigate(route) {
switch (route) {
case '/dashboard':
const { renderDashboard } = await import('./routes/dashboard.js');
renderDashboard();
break;
case '/settings':
const { renderSettings } = await import('./routes/settings.js');
renderSettings();
break;
}
}
initApp();
Rollup's static analysis detects these import() calls at build time and creates separate chunks for dashboard.js and settings.js plus their unique dependencies.
Building and Verifying Output
Run the production build:
npx rollup -c
Expected dist/ contents:
entry-.js— main entry chunkvendor-.js— shared npm dependencieschunk-.js— one per dynamic import boundary (e.g., dashboard, settings).js.mapfiles for each chunk (source maps)
Verification Checklist
- File inspection: Confirm multiple
.jsfiles exist indist/with hash suffixes. - Network tab test: Serve
dist/(e.g.,npx serve dist), open the HTML entry page, trigger a lazy route, and verify a new chunk request appears in DevTools Network panel. - Duplication check: Run
npx rollup-plugin-visualizer --opento visualize chunk sizes and ensure no module appears in more than one chunk. - Source map validation: Set a breakpoint in original source (e.g.,
src/routes/dashboard.js) inside browser DevTools; execution should pause at the correct line.
Common Failure Modes and Fixes
Missing Chunks
If expected lazy chunks don't appear, the dynamic import argument is likely not statically analyzable. Rollup only splits on string literals:
// ❌ Variable path — defeats static analysis
const route = '/dashboard';
import(`./routes${route}.js`);
// ✅ Static string — enables splitting
import('./routes/dashboard.js');
Refactor variable paths to static strings or use a plugin like @rollup/plugin-dynamic-import-vars if dynamic paths are unavoidable.
Vendor Chunk Too Large
If the vendor chunk exceeds ~200 KB gzipped, split heavy libraries into named chunks:
manualChunks: (id) => {
if (id.includes('node_modules')) {
if (id.includes('lodash') || id.includes('date-fns')) return 'utils';
if (id.includes('react') || id.includes('react-dom')) return 'react';
return 'vendor';
}
}
This creates utils-.js, react-.js, and a smaller vendor-.js.
Runtime Errors in Browser
- Ensure the HTML loads the entry chunk with
<script type=module src="entry-.js"></script>. - Verify
output.chunkFileNamesuses[hash]so updated chunks get new URLs (browsers cache aggressively). - For older browser targets, consider
format: 'systemjs'with the SystemJS loader instead of native ESM.
Watch Mode Limitation
Running rollup -cw (watch mode) does not re-evaluate manualChunks when new files are added. After creating a new dynamic import boundary, stop and restart the build to incorporate the new chunk.
Limitations
- Automatic splitting requires static
import()arguments; dynamic expressions defeat analysis. format: 'esm'requires modern browsers (ES2015 modules) or a module-shim polyfill for legacy support.manualChunksruns per module; returningnull/undefinedlets Rollup decide, while a string forces a named chunk.
Quick Validation Command
After configuration changes, run this one-liner to confirm multi-chunk output:
npx rollup -c --configPlugin esm && ls -la dist/*.js
You should see at least three .js files (entry, vendor, and one feature chunk) with distinct hashes.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.