0Pricing
React Academy · Lesson

Bundle Analysis & Code Splitting Strategy

Analyse bundle size with rollup-plugin-visualizer and set a code splitting strategy by route.

Bundle Analysis & Code Splitting Strategy is a free React Academy lesson on CoddyKit — lesson 2 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 React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Bundle Size Matters

Large JavaScript bundles delay Time To Interactive. Every KB of JS must be downloaded, parsed, and executed before the page becomes interactive — especially on slow mobile networks.

Analyzing with rollup-plugin-visualizer

In Vite projects, use the visualizer plugin to generate a treemap of your bundle showing which modules take the most space.

// vite.config.ts
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [
    visualizer({ open: true, gzipSize: true, brotliSize: true })
  ],
});

// After build, open the generated HTML file to explore the treemap

Next.js Bundle Analyzer

Use @next/bundle-analyzer to analyze server and client bundles in Next.js.

npm install @next/bundle-analyzer

// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

module.exports = withBundleAnalyzer({});

// Run:
// ANALYZE=true npm run build

Route-Based Code Splitting

The most impactful splitting: load each route's code only when the user navigates to it. React Router with lazy() and Next.js App Router do this automatically.

// React Router v6 with lazy loading
import { lazy, Suspense } from 'react';

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

<Routes>
  <Route path="/dashboard" element={<Suspense fallback={<Loading />}><Dashboard /></Suspense>} />
  <Route path="/settings" element={<Suspense fallback={<Loading />}><Settings /></Suspense>} />
</Routes>

Component-Level Code Splitting

Defer loading heavy components (maps, charts, editors) until they're needed using lazy().

const MonacoEditor = lazy(() => import('@monaco-editor/react'));
const MapView = lazy(() => import('./MapView'));

function ProductEditor({ showMap }) {
  return (
    <>
      <Suspense fallback={<EditorSkeleton />}><MonacoEditor /></Suspense>
      {showMap && <Suspense fallback={<MapSkeleton />}><MapView /></Suspense>}
    </>
  );
}

Dynamic Import for Conditional Features

Import large libraries only when a feature is activated to avoid loading them for all users.

async function exportToPDF() {
  const { default: jsPDF } = await import('jspdf'); // ~300KB — loaded on demand
  const doc = new jsPDF();
  doc.text('Hello', 10, 10);
  doc.save('export.pdf');
}

Tree Shaking

Modern bundlers eliminate unused exports (dead code). Ensure your dependencies support ESM (not CJS) for tree shaking to work, and avoid importing entire libraries when you only use one function.

// Bad — imports entire lodash (~70KB):
import _ from 'lodash';
const result = _.debounce(fn, 300);

// Good — imports only debounce (<2KB):
import debounce from 'lodash/debounce';
// or with tree-shaking-friendly lodash-es:
import { debounce } from 'lodash-es';

Preloading Critical Chunks

Use <link rel='modulepreload'> or Webpack magic comments to preload the next page's chunk while the user is on the current page.

// Webpack magic comment — preload on hover:
const Dashboard = lazy(() => import(/* webpackPrefetch: true */ './Dashboard'));
// or preload (higher priority):
const Dashboard = lazy(() => import(/* webpackPreload: true */ './Dashboard'));

Analyzing Third-Party Impact

Use bundlephobia.com or Import Cost VS Code extension to see the gzipped size of any npm package before installing it.

Setting a Bundle Budget

Set a size limit per route in Webpack or Vite config. The build fails if a chunk exceeds the budget, catching accidental size regressions in CI.

// vite.config.ts
build: {
  rollupOptions: {
    output: {
      manualChunks: {
        'vendor-react': ['react', 'react-dom'],
        'vendor-router': ['react-router-dom'],
      },
    },
  },
  chunkSizeWarningLimit: 200, // warn at 200KB
},

Quick Check

What is the most impactful code splitting strategy for React SPAs with many pages?

Recap

Analyze bundles with rollup-plugin-visualizer or @next/bundle-analyzer. Use route-based and component-level lazy() splits. Apply tree shaking by importing only what you use. Set size budgets in CI and use prefetch/preload hints for the next likely route.

Frequently asked questions

Is the “Bundle Analysis & Code Splitting Strategy” lesson free?

Yes — the full text of “Bundle Analysis & Code Splitting Strategy” is free to read here on the web, and the React 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 React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Bundle Analysis & Code Splitting Strategy”?

Analyse bundle size with rollup-plugin-visualizer and set a code splitting strategy by route. You practise React 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 React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Bundle Analysis & Code Splitting Strategy” 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 React Academy lesson?

Yes. Every React 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

  1. Measuring Core Web Vitals in React Apps
  2. Bundle Analysis & Code Splitting Strategy
  3. Image & Font Optimisation in React
  4. Reducing INP: Event Handler Optimisation
← Back to React Academy