A visitor who only wants your shop's Home page also downloads the Admin page, along with a 180 KB chart library only admins use. On a 1.6 Mbps connection, that visitor waits about 2.55 seconds for 510 KB, when all they need is 220 KB.
Code splitting means cutting your app's JavaScript into several smaller files (called chunks), so the browser only downloads the chunks the page being opened needs. The rest is downloaded later, when it's actually used. It's like buying a 20-volume encyclopedia: a smart shop sends the volume you want to read now first, and the other volumes when you ask for them. You can start reading much sooner. Here the encyclopedia is all of your app's JavaScript, each volume is one chunk, and the volume sent first is the chunk for the page being opened.
Bundles and chunks
When you run npm run build, a bundler (Vite, webpack, Rollup, esbuild) collects all your JavaScript files and the libraries you use. Then it joins them into files ready to send. That joined result is called a bundle. Without code splitting, everything goes into one bundle, including pages the visitor never opens.
These are the parts of the online shop's JavaScript in the Lab. React is a popular library for building interfaces, and the router picks which page to show for the URL:
| Part | Size | Used on |
|---|---|---|
| React, React DOM, router | 150 KB | every page |
| App and layout (header, menu) | 40 KB | every page |
Home.jsx |
30 KB | / |
Products.jsx |
50 KB | /products |
Admin.jsx |
60 KB | /admin |
SalesChart.jsx and its chart library |
180 KB | /admin, after the Show chart button is clicked |
510 KB in total. Say the network is 1.6 Mbps, roughly 200 KB per second. One whole bundle takes about 2.55 seconds just to download. But a visitor opening the Home page only needs 220 KB. And once downloaded, every KB of JavaScript still has to be parsed and run, so code nobody uses still slows the page down.
A chunk is a piece of the bundle that becomes a file of its own. You don't cut it by hand. You just mark "this part may load later", and the bundler makes the chunk for you.
import() loads a module when it's needed
That mark is the dynamic import, import(). This is how it differs from a normal import (a module is one JavaScript file that has exports):
// Static import: written at the very top of the file, goes straight into the main bundle
import { formatPrice } from './utils.js';
// Dynamic import: called like a function, whenever you like
chartButton.addEventListener('click', async () => {
const { drawChart } = await import('./chart.js'); // only downloaded now
drawChart(salesData);
});
import ... from(static) is only allowed at the top level of a file, outside any function orifblock. The module is always loaded together with that file.import('./chart.js')is called like a function and returns a Promise. The Promise resolves to the module's contents: named exports become properties (drawChart), and the default export is under.default.- Because it returns a Promise, use
await(or.then). While you wait, the file is being downloaded. - Every
import()is a sign for the bundler:chart.jsand everything onlychart.jsuses are split into a chunk of their own.
So the syntax that loads a module at runtime (while the page is running) is import().
Splitting by route with React.lazy
The most common way: every page (route) becomes its own chunk. In React, use lazy and Suspense:
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router';
import Home from './pages/Home.jsx'; // the first page, stays static
// Becomes its own chunk, only downloaded when its route is opened
const Products = lazy(() => import('./pages/Products.jsx'));
const Admin = lazy(() => import('./pages/Admin.jsx'));
export default function App() {
return (
<Suspense fallback={<p>Loading the page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />} />
<Route path="/admin" element={<Admin />} />
</Routes>
</Suspense>
);
}
lazy(() => import(...))makes a component whose code is only downloaded the first time it renders (is drawn on the page). The file must have anexport defaultholding the component.<Suspense fallback={...}>shows the fallback (a temporary view) while the chunk downloads. The lazy components must be inside aSuspense, so there is something to show while you wait.Homestays a static import, because almost every visitor opens it first.
As a result, the first download is just React and the router (150 KB), the layout (40 KB) and the Home page (30 KB): 220 KB, down from 510 KB. The download time drops from about 2.55 seconds to 1.1 seconds.
Splitting by component: load on click
The Admin page has a sales chart with a 180 KB library, yet the chart only appears after a button is clicked. Split that too. In this code, useState(false) makes a value shown that starts as false, and the Show chart button changes it to true:
import { lazy, Suspense, useState } from 'react';
const SalesChart = lazy(() => import('./SalesChart.jsx'));
export default function Admin() {
const [shown, setShown] = useState(false);
return (
<main>
<h1>Admin</h1>
<button onClick={() => setShown(true)}>Show chart</button>
{shown && (
<Suspense fallback={<p>Loading the chart...</p>}>
<SalesChart />
</Suspense>
)}
</main>
);
}
As long as shown is still false, SalesChart never renders, so its chunk is never downloaded. Moving to Admin now downloads only 60 KB. The 180 KB chart library waits until the button is clicked.
The price: waiting when you move
Code splitting doesn't remove code. It only moves the time when the code is downloaded. If Admin and its chart are one chunk, a visitor moving to Admin waits for 240 KB, about 1.2 seconds, plus one round trip to the server. All they see in that time is the fallback.
That's why you split the parts that are big and rarely needed at the start: other pages, editors, charts, maps. Parts every page uses (the layout, the login button) stay in the main bundle. Splitting into too many small chunks also has a cost, because every chunk is one more request. To remove the pause when moving, the browser can be asked to quietly download the next page's chunk ahead of time. The next lesson, Resource Hints, shows how.
💡 Tree shaking needs ES modules
Besides splitting it, a bundle can be made smaller with tree shaking: the bundler drops exports that are never imported. If utils.js has 20 functions and you only use formatPrice, the rest stays out of the bundle.
The condition is that the code is written as an ES module (using import and export). Then the bundler can tell from the text alone what's used. CommonJS (an older way of writing modules, with require and module.exports) generally can't be tree-shaken. A common example: lodash (CommonJS) is included whole even if you only need debounce, while lodash-es (the ES module version) only includes what you import.
🎯 Find what makes the bundle fat
Before splitting, check what's big. vite build already prints the size of every chunk. To see what's inside by module, use rollup-plugin-visualizer (Vite and Rollup) or webpack-bundle-analyzer (webpack). Both draw a box per module: the bigger the box, the bigger the module. A big library used by only one page is the first candidate for a chunk.
⚠️ Errors and delays from splitting the wrong way
- A static
importinside anifor a function.if (isAdmin) { import Chart from './Chart.jsx' }is a SyntaxError, so the file doesn't run at all. To load something later, useimport(). - A lazy component without
Suspense. React needs a<Suspense>around it to know what to show while the chunk downloads. - Forgetting
export default.lazy()takes the default export. If the file only has named exports, it getsundefinedand React throws an error. - Splitting what every page uses. A lazy layout or header only adds a request and a pause at the start, and saves nothing.
TL;DR: Code splitting cuts the JavaScript bundle (all your app's code joined together) into chunks, smaller files that load as they're needed. You mark the parts that may load later with import(): called any time, it returns a Promise, and the bundler turns its module into a chunk of its own. In React, lazy(() => import('./Admin.jsx')) inside <Suspense> makes every route (page) a chunk. In the Lab, the first download drops from 510 KB to 220 KB. A heavy component that appears after a click (a 180 KB chart) gets split too. The price: visitors wait when they move to another page. So split what's big and rarely needed at the start, not the layout every page uses. Tree shaking drops unused exports, but it's only reliable with ES modules (code that uses import and export).
⚡ One bundle, many chunks
Meaning: A bundler (a tool such as Vite) joins all your app's JavaScript into a bundle, a file ready to send. Without code splitting (cutting the bundle into smaller files called chunks), pages nobody opens get downloaded too. In the Lab, a Home page visitor only needs 220 KB but downloads 510 KB.
⚡ import() loads a module later
Write:
const { drawChart } = await import('./chart.js');
Guess first: what does import('./chart.js') return?
A Promise, which resolves to the module's contents. That's why you wait for it with await. The bundler also turns chart.js into a chunk of its own.
Meaning: import() is called a dynamic import. The file chart.js is only downloaded when this line runs, and drawChart is a function taken from that file. A static import ... from is only allowed at the top of a file. To load a module (a JavaScript file) at runtime, while the page is running, use import().
⚡ Every route becomes a chunk
Write:
const Admin = lazy(() => import('./pages/Admin.jsx'));
Meaning: In React, lazy() makes an Admin component whose code is only downloaded the first time that component renders (is drawn). That happens when the Admin route (page) is opened. The <Suspense fallback={...}> around it shows a temporary view while you wait. In the Lab, the first download drops from 510 KB to 220 KB. A layout every page uses stays a static import.