4 Hours

6. Code Splitting: Reducing Initial Bundle Size

Optimization

Code splitting is the technique of breaking your application into smaller chunks that can be loaded on demand. This reduces the initial bundle size, improving load times and user experience. Code splitting is essential for large applications.

The key insight is that users don't need all your code upfront. The initial page only needs the code for that page. Other code can be loaded lazily when needed. Code splitting enables this pattern, reducing initial load time by 50-80%.

This module covers dynamic imports, React.lazy, Suspense, and Webpack's splitChunks.

Types of Code Splitting

There are three main types of code splitting: entry point splitting (multiple entry points), vendor splitting (separating third-party libraries), and dynamic imports (lazy loading on demand). Entry point splitting separates different pages. Vendor splitting separates third-party libraries for better caching. Dynamic imports load code only when needed.

Each type serves a different purpose. Entry point splitting is good for multi-page apps. Vendor splitting is good for caching. Dynamic imports are good for route-based lazy loading.

Dynamic Imports and React.lazy

Dynamic imports are the foundation of code splitting in modern JavaScript. The import() function returns a promise that resolves to the module. This allows code to be loaded on demand. React.lazy works with dynamic imports to load components lazily. Suspense handles the loading state.

Route-based splitting is the most common pattern. Each route loads only the code it needs. This can cut initial bundle size by 50-80%.

JavaScript
// Dynamic import
import('./math.js').then(module => {
  console.log(module.add(2, 3));
});

// React.lazy with Suspense
import React, { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./pages/Dashboard'));
const Profile = lazy(() => import('./pages/Profile'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...
}> } /> } /> } /> ); } // Named exports with React.lazy const LazyComponent = lazy(() => import(./components/HeavyComponent).then(module => ({ default: module.HeavyComponent, })) ); // Prefetching const prefetchDashboard = () => { import(./pages/Dashboard); }; // Prefetch on hover Dashboard ;

Webpack splitChunks

Webpack's splitChunks configuration automatically splits code into chunks. You can configure cache groups for different types of code. The default configuration works for many projects, but custom configuration can optimize specific patterns.

Common configurations: separating vendor code (node_modules), separating common code (shared modules), and separating runtime code. splitChunks can be fine-tuned for performance.

JavaScript
// webpack.config.js - splitChunks configuration
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all',
      minSize: 20000,
      maxSize: 244000,
      minChunks: 1,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      cacheGroups: {
        // Vendor chunk (node_modules)
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all',
          priority: 10,
        },
        // React and ReactDOM
        react: {
          test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
          name: 'react-vendor',
          chunks: 'all',
          priority: 20,
        },
        // UI library (e.g., Material-UI)
        ui: {
          test: /[\\/]node_modules[\\/](@mui|@emotion)[\\/]/,
          name: 'ui-vendor',
          chunks: 'all',
          priority: 20,
        },
        // Common chunks
        common: {
          minChunks: 2,
          priority: 5,
          reuseExistingChunk: true,
        },
      },
    },
  },
};

Try It Yourself: Code Splitting

Follow these steps to implement code splitting.

Step 1: Create a project with multiple routes
// App.js<br>import { BrowserRouter, Routes, Route, Link } from <strong><code>react-router-dom;
import { lazy, Suspense } from react;

const Home = lazy(() => import(./pages/Home));
const About = lazy(() => import(./pages/About));
const Dashboard = lazy(() => import(./pages/Dashboard));

export default function App() {
return (


Loading...
}>

} />
} />
} />



);
}

Step 2: Configure Webpack splitChunks
Add the splitChunks configuration above.

Step 3: Build and analyze
npm run build<br>npx webpack-bundle-analyzer dist/stats.json

Step 4: Add prefetching
Add prefetching for routes.

Try It Yourself: Add code splitting for a large component. Implement lazy loading for modals. Add prefetching for navigation.

Knowledge Check

Ready to test your understanding of 6. Code Splitting: Reducing Initial Bundle Size?

Back