Code Splitting and Lazy Routes
Use dynamic import() to split the bundle at route boundaries, lazy-load React and Vue components, and monitor chunk sizes in the build output.
Why Code Split?
A monolithic JavaScript bundle forces every visitor to download every line of code in your app — even features they never use. Code splitting breaks the bundle into chunks loaded on demand.
Dynamic import()
import('./module') returns a Promise that resolves to the module. Bundlers (Vite, webpack) see this and emit a separate chunk loaded at runtime.
// Without split — entire heavy lib in main bundle:
import { generateChart } from 'heavy-chart-lib';
// With split — loaded only when needed:
button.addEventListener('click', async () => {
const { generateChart } = await import('heavy-chart-lib');
generateChart(data);
});All lessons in this course
- Core Web Vitals: LCP FID CLS
- Lighthouse Audits and Scoring
- Image Optimization: lazy loading formats WebP
- Code Splitting and Lazy Routes