Vite Code Splitting & Dynamic Import
A user opening your home page shouldn't have to download the code for the admin dashboard, the chart library and the PDF exporter. Code splitting breaks the bundle into chunks that load only when needed — and in Vite you get it simply by using dynamic import().
Static vs dynamic
// static: bundled into the main chunk, loaded up front
import { formatDate } from './utils/date.js';
// dynamic: becomes a separate chunk, loaded on demand
button.addEventListener('click', async () => {
const { renderChart } = await import('./charts/sales.js');
renderChart(document.querySelector('#chart'));
});After the build:
npm run build> my-app@0.0.0 build
> vite build
vite v8.3.4 building client environment for production...
✓ 9 modules transformed.
dist/index.html 0.48 kB │ gzip: 0.31 kB
dist/assets/sales-BvT2kQ1n.css 0.62 kB │ gzip: 0.35 kB
dist/assets/index-DiwrgTda.css 1.24 kB │ gzip: 0.63 kB
dist/assets/sales-Ck8pL3Xz.js 48.71 kB │ gzip: 17.02 kB
dist/assets/index-Dq9mR2sA.js 4.36 kB │ gzip: 2.01 kB
✓ built in 211ms
The chart code (and its CSS) is in its own sales-*.js file. The main bundle stays small.
Seeing lazy loading happen
This playground simulates two chunks as data: URLs. The "chart" chunk is only fetched and evaluated when it's needed, and a second request reuses the cached module:
const chunk = (src) => 'data:text/javascript,' + encodeURIComponent(src);
const salesChunk = chunk(`
console.log(' [network] sales chunk downloaded & evaluated');
export function renderChart(data) {
return data.map((n) => '#'.repeat(n)).join(' | ');
}
`);
(async () => {
console.log('app started (main chunk only)');
console.log('user clicks "Show chart"');
const { renderChart } = await import(salesChunk);
console.log(' ' + renderChart([3, 5, 2]));
console.log('user clicks again');
const again = await import(salesChunk);
console.log(' ' + again.renderChart([1, 4]));
})();app started (main chunk only)
user clicks "Show chart"
[network] sales chunk downloaded & evaluated
### | ##### | ##
user clicks again
# | ####
Route-based splitting
The most effective place to split is per page/route. Framework routers support it directly:
// React
const Admin = React.lazy(() => import('./pages/Admin.jsx'));
// Vue Router
const routes = [
{ path: '/', component: () => import('./pages/Home.vue') },
{ path: '/admin', component: () => import('./pages/Admin.vue') },
];
// Vanilla: import.meta.glob gives you one lazy loader per page
const pages = import.meta.glob('./pages/*.js');Shared chunks and preloading
If two lazy chunks both import utils/format.js, the bundler extracts it into a shared chunk so it is downloaded once. Vite also optimizes the loading waterfall: when sales.js needs format.js, Vite requests both in parallel instead of one after the other, and adds <link rel="modulepreload"> tags for the entry's dependencies in index.html.
Without preload: main.js ──▶ sales.js ──▶ format.js (3 round-trips)
With Vite: main.js ──▶ sales.js + format.js (2 round-trips)CSS imported by a lazy chunk is split too (build.cssCodeSplit: true) and is loaded together with the chunk.
Manual chunks
Sometimes you want control: for example a vendor chunk for big libraries that change rarely (better caching across deploys). In Vite 8 this is configured with Rolldown's codeSplitting groups:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
build: {
rolldownOptions: {
output: {
codeSplitting: {
groups: [
{ name: 'react-vendor', test: /node_modules[\\/](react|react-dom|scheduler)[\\/]/ },
{ name: 'vendor', test: /node_modules/ },
],
},
},
},
},
});The older Rollup-style function still works for migration (output.manualChunks(id) { if (id.includes('node_modules')) return 'vendor'; }), but it is deprecated in Rolldown.
How such a grouping decides chunk names — first matching group wins:
const groups = [
{ name: 'react-vendor', test: /node_modules[\\/](react|react-dom|scheduler)[\\/]/ },
{ name: 'vendor', test: /node_modules/ },
];
const modules = [
'/app/src/main.jsx',
'/app/node_modules/react/index.js',
'/app/node_modules/react-dom/client.js',
'/app/node_modules/date-fns/format.js',
'/app/src/pages/Admin.jsx',
];
for (const id of modules) {
const group = groups.find((g) => g.test.test(id));
console.log(id.padEnd(40), '->', group ? group.name : '(default chunking)');
}/app/src/main.jsx -> (default chunking)
/app/node_modules/react/index.js -> react-vendor
/app/node_modules/react-dom/client.js -> react-vendor
/app/node_modules/date-fns/format.js -> vendor
/app/src/pages/Admin.jsx -> (default chunking)
Warning: Too many tiny chunks can be slower than a few medium ones (more requests, less compression). Split by route and by large, rarely-changing libraries — not by every file.
Dynamic import with variables
Vite supports template literals in dynamic imports when the path starts with ./ or ../ and ends with an extension:
const lang = navigator.language.slice(0, 2);
const messages = await import(`./locales/${lang}.js`); // every ./locales/*.js becomes a chunkHandling load errors
After a deploy, users with an old tab open may try to load a chunk that no longer exists. Vite fires a vite:preloadError event you can use to reload the page:
window.addEventListener('vite:preloadError', (event) => {
event.preventDefault();
window.location.reload(); // get the new index.html and chunk names
});Test yourself
How do you create a separate chunk in a Vite app?
- Add a
// @chunkcomment - Use dynamic
import() - Put the file in public/
- Use
require()
Why put large third-party libraries in a separate vendor chunk?
- It makes them smaller
- They change rarely, so the chunk stays cached across app deploys
- Browsers require it
- To disable tree-shaking
Which event can you listen to when a lazy chunk fails to load after a deploy?
- chunkerror
- vite:preloadError
- error:import
- hmr:fail