Lazy-Load Route Chunks in Vite
Split routes into dynamic imports so the initial bundle stays small and heavy views load on demand.
Task
Convert static route imports to dynamic imports to split the bundle by route.
When to use this
The initial bundle includes every route, so a simple landing page downloads admin and settings code too.
Prerequisites
- A Vite project with routing
- A bundler analyser
- A route structure
Steps
1. Replace static imports with dynamic route imports.
const routes = [
{ path: '/', component: () => import('./pages/Home.vue') },
{ path: '/admin', component: () => import('./pages/Admin.vue') },
];Expected output: Each route becomes its own chunk loaded only when visited.
2. Verify the initial bundle shrank.
npx vite build
npx source-map-explorer dist/assets/*.jsExpected output: The entry chunk no longer contains admin code, and route chunks appear separately.
Troubleshooting
Problem
Loading spinner on every navigation
Solution
Preload likely next routes and show a lightweight fallback.
Problem
Chunks too granular
Solution
Group related views into shared chunks to avoid waterfall requests.
Limitations
- Adds a network round trip per route.
- Does not help if a heavy library is in the entry chunk.
- Requires a fallback UI during load.
What this recipe does
Convert static route imports to dynamic imports to split the bundle by route.
The initial bundle includes every route, so a simple landing page downloads admin and settings code too.
Prerequisites
- A Vite project with routing
- A bundler analyser
- A route structure
Procedure
- Replace static imports with dynamic route imports.
const routes = [
{ path: '/', component: () => import('./pages/Home.vue') },
{ path: '/admin', component: () => import('./pages/Admin.vue') },
];
Expected result: Each route becomes its own chunk loaded only when visited.
- Verify the initial bundle shrank.
npx vite build
npx source-map-explorer dist/assets/*.js
Expected result: The entry chunk no longer contains admin code, and route chunks appear separately.
How to confirm it worked
Run the commands above and confirm every expected result in order. If a step does not produce the stated output, use the troubleshooting notes before continuing. A passing run shows the entry bundle drops in size and heavy routes load as separate chunks on demand.
Troubleshooting
Loading spinner on every navigation — Preload likely next routes and show a lightweight fallback.
Chunks too granular — Group related views into shared chunks to avoid waterfall requests.
Limitations
- Adds a network round trip per route.
- Does not help if a heavy library is in the entry chunk.
- Requires a fallback UI during load.