What Is Code Splitting? A Detailed Guide
Author: @Tranloi2k
On this page
What Is Code Splitting? A Detailed Guide
Author: @Tranloi2k
Created: 2025-09-24
Description: An explanation of code splitting, its benefits, how to use it in React/Webpack, and real-world tips.
1. What Is Code Splitting?
Definition:
Code Splitting is a technique for splitting an application into multiple smaller bundles, loading only the part needed at the moment the user visits it. Instead of loading the entire application up front, code splitting optimizes speed, reduces download size, and improves user experience.
2. Benefits of Code Splitting
- Faster initial page load: only critical code loads first, the rest loads as needed.
- Bandwidth savings: users only download the parts they actually visit.
- Optimized performance: less JS to parse and execute, making the browser smoother.
- Supports lazy loading: combine with lazy loading to load components/modules only when truly needed.
3. Using Code Splitting in React
a. Component-Level Splitting
Using React.lazy and Suspense
React provides React.lazy() to dynamically load a component when needed, combined with Suspense to display a loading UI.
Example:
import React, { Suspense, lazy } from 'react';
// Split the component, only load it when rendered
const UserProfile = lazy(() => import('./UserProfile'));
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<UserProfile />
</Suspense>
</div>
);
}
b. Router-Based Splitting
Code splitting with React Router
Only load each page when the user navigates to that route.
Example:
import { lazy } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./Home'));
const Admin = lazy(() => import('./Admin'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/admin" element={<Admin />} />
</Routes>
</Suspense>
);
}
4. Code Splitting with Webpack (In Depth)
Webpack is a popular tool that splits bundles effectively. Here are detailed code splitting techniques with Webpack:
a. Dynamic Splitting
Dynamic import() (splitting a bundle at runtime)
Webpack automatically splits code into smaller bundles when you use the dynamic import syntax:
// Only load the module when needed
button.onclick = () => {
import('./moduleA')
.then(module => {
module.doSomething();
});
};
Explanation:
- When the user clicks the button, Webpack creates a separate bundle for
moduleA(usually named something likemoduleA.[hash].js) and only loads it when needed, instead of including it in the main bundle. - Can also be used with async/await:
js
async function loadModule() { const module = await import('./moduleA'); module.doSomething(); }
b. Entry Points Splitting
Multiple Entry Points
You can configure multiple entry points in Webpack to create separate bundles for independent parts of your application (e.g., admin, user).
webpack.config.js
module.exports = {
entry: {
main: './src/index.js',
admin: './src/admin.js',
landing: './src/landing.js'
},
output: {
filename: '[name].bundle.js',
path: __dirname + '/dist'
}
};
Explanation:
- Webpack will generate the files:
main.bundle.js,admin.bundle.js,landing.bundle.js. - You only need to load the appropriate bundle on each page.
c. SplitChunksPlugin (Optimizing Shared Bundles)
Webpack provides optimization.splitChunks to automatically split shared modules (e.g., the React library, lodash) into a separate bundle.
webpack.config.js
module.exports = {
// ...other configuration
optimization: {
splitChunks: {
chunks: 'all', // split both async and sync chunks
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
};
Explanation:
- Libraries from
node_modulesget bundled intovendors.js. - These small bundles are cached effectively by the browser, making subsequent loads faster.
d. Prefetch & Preload
Webpack supports magic comment directives to optimize preloading bundles when needed:
// Prefetch: load when the browser is idle
import(/* webpackPrefetch: true */ './moduleA');
// Preload: load as soon as possible (high priority)
import(/* webpackPreload: true */ './moduleB');
Explanation:
- Helps optimize the user experience, e.g., preloading the admin bundle when the user is about to navigate to the admin page.
e. Combining with React and React Router
When using code splitting in React, Webpack automatically generates small bundles for each page/component when you use React.lazy or dynamic imports.
5. Things to Watch Out for with Code Splitting
- Always have a loading UI (
fallback) while a dynamic component loads. - Test real-world performance with tools like Lighthouse.
- Ensure important parts (critical JS) always load first.
- With SSR (Server Side Rendering), you need additional configuration to support code splitting correctly.
- Avoid splitting into too many small pieces, which leads to a stream of small, repeated requests.
- Optimize caching for shared bundles (vendors.js) to reduce load on subsequent visits.
6. Summary
Code splitting is an important technique for optimizing page-load speed and user experience in modern web applications. In React, combine it with lazy loading and Suspense for maximum effectiveness! With Webpack, take advantage of techniques like dynamic import, multi-entry, and splitChunks to split your project's bundles sensibly.
