Frontend Case Studies

Topic F11

Bundle splitting and tree shaking

The module graph, cutting it per page, and dropping code that's never used.

9 min · intermediate

Watch: one big bundle downloads all the code up front. Split by page, the first visit downloads only what it needs.

45 KB20 KB15 KB30 KB160 KB25 KB120 KBmodulesreactapphomedashboardchart libsettingseditor lib
  • moving now
  • finished / the result
Step 1 of 3

An app with three pages. The dashboard uses a big chart library; settings uses an editor library. Block height follows size.

Code this page doesn't use doesn't need downloading yet.

Why JavaScript size matters

JavaScript costs more than an image of the same size. Once downloaded it has to be parsed, compiled and run on the main thread, and the page doesn't respond meanwhile (see the event loop topic). On a mid-range phone, 400 KB of JavaScript can take seconds before the page responds to taps.

Code splitting

A dynamic import() tells the bundler "cut the graph here". Everything only reachable through that import goes into a separate chunk that's downloaded when it's called. Frameworks like Next.js and React Router split per route automatically. Modules used by many chunks (like React) go into a shared chunk so they aren't downloaded twice.

Code, for programmersLoading a heavy library only when needed
// the chart library (160 KB) is not in the main bundle
const Chart = lazy(() => import("./Chart"));

function Dashboard() {
  return (
    <Suspense fallback={<ChartSkeleton />}>
      <Chart data={data} />
    </Suspense>
  );
}

// or on demand, e.g. when the user clicks Export
button.onclick = async () => {
  const { exportPdf } = await import("./export-pdf");
  exportPdf(report);
};

Tree shaking

The bundler walks the graph from the entry point and keeps only the exports actually reached, like a DFS (Module 8) marking visited nodes. The rest is dropped. This only works with ES modules (import/export) that can be analysed at build time, and only if modules have no side effects when imported.

Code, for programmersImports that can and can't be shaken
import _ from "lodash";             // the whole library (~70 KB): CommonJS, not shakeable
import debounce from "lodash/debounce";  // just one function
import { debounce } from "lodash-es";  // ES modules: unused functions are dropped

import * as icons from "./icons";   // fine if you only use icons.Search...
icons[name];                        // ...but a dynamic lookup keeps them all

Quiz

  1. What does a dynamic import() do for the bundler?

  2. Why does import _ from 'lodash' make a big bundle?

  3. Why is 400 KB of JavaScript costlier than a 400 KB image?

0 of 3 answered.