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.
Code Splitting and Lazy Routes is a free Frontend Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
});React.lazy() — Component-Level Splitting
React.lazy(() => import('./Heavy')) creates a component that loads its code only when first rendered. Wrap it in <Suspense> to show a fallback while loading.
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<Dashboard />
</Suspense>
);
}Route-Based Splitting in React Router
Each route gets its own chunk — users only download code for the pages they visit.
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import { lazy, Suspense } from 'react';
const Home = lazy(() => import('./pages/Home'));
const Profile = lazy(() => import('./pages/Profile'));
const Admin = lazy(() => import('./pages/Admin'));
const router = createBrowserRouter([
{ path: '/', element: <Suspense fallback={<Spinner/>}><Home /></Suspense> },
{ path: '/profile', element: <Suspense fallback={<Spinner/>}><Profile /></Suspense> },
{ path: '/admin', element: <Suspense fallback={<Spinner/>}><Admin /></Suspense> }
]);Vue 3 Async Components
Vue offers defineAsyncComponent for the same pattern.
import { defineAsyncComponent } from 'vue';
const Dashboard = defineAsyncComponent(() =>
import('./Dashboard.vue')
);
// Use in template like a normal componentVue Router Lazy Routes
Vue Router supports dynamic imports in route definitions — chunks are emitted per route.
const routes = [
{ path: '/', component: () => import('./pages/Home.vue') },
{ path: '/profile', component: () => import('./pages/Profile.vue') },
{ path: '/admin', component: () => import('./pages/Admin.vue') }
];Webpack Magic Comments
Hint at chunk names and prefetch behaviour via webpack 'magic comments' inside the import statement.
const Profile = lazy(() =>
import(/* webpackChunkName: "profile", webpackPrefetch: true */ './Profile')
);
// Vite supports a subset; @vite-ignore for special casesPrefetch vs Preload
prefetch: download chunk during idle time, for likely-next navigations. preload: download now with high priority, for the current route's critical chunks. Use prefetch for hover-on-link, preload for known imminent needs.
Bundle Analyzer
Use rollup-plugin-visualizer (Vite) or webpack-bundle-analyzer to visualise chunk sizes. Look for: oversized chunks, duplicated dependencies, libraries you forgot to tree-shake.
// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer';
export default {
plugins: [visualizer({ open: true, gzipSize: true })]
};Vendor Chunk Splitting
Split third-party libraries into a separate vendor chunk that changes less often than your app code — browsers can keep it cached across deploys.
// vite.config.ts
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
react: ['react', 'react-dom'],
ui: ['@radix-ui/react-dialog', '@radix-ui/react-tooltip']
}
}
}
}
};When NOT to Split
Tiny chunks (under 20KB) hurt more than they help — the HTTP overhead exceeds the bundle savings. Don't split every component; split at route boundaries and around genuinely heavy features.
Quick Check
What does React's lazy() wrapper need to be paired with to render correctly?
Recap: Code Splitting
Dynamic import() emits separate chunks. React.lazy + Suspense for component splitting. Lazy route components in React Router / Vue Router. Use prefetch for likely-next chunks, preload for critical. Bundle analyzer reveals waste. Split vendor libs for cacheability. Avoid micro-chunks under 20KB.
Frequently asked questions
Is the “Code Splitting and Lazy Routes” lesson free?
Yes — the full text of “Code Splitting and Lazy Routes” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “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. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Code Splitting and Lazy Routes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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