Faizo

Writing · Performance · Web · Front end

Cutting 30 KB from a boot bundle by moving module boundaries

Lazy loading didn't shrink my first-load JavaScript until I learned that a bundler places each module in one chunk, whole. How to find and split those modules.

DWEEB is a single-page editor. Its build has a budget for the "critical" bundle, meaning the JavaScript and CSS a first visit must download before the editor works, and the build fails when the budget is exceeded. For a while that budget was 182 KB gzipped and the bundle sat at 181.0 KB. Every new feature turned into a negotiation over a few hundred bytes.

The app already lazy-loaded every dialog. The remaining weight was not in the obviously optional screens. It was in code that looked like it was part of the first screen and wasn't, and in modules that were dragged into the boot chunk by a single import. Fixing both took the critical bundle from 588,815 to 477,114 bytes raw, and from 181,014 to 150,427 bytes gzipped, about 17% less to download. The budget is now 160 KB.

Rule one: the boot path carries only what the first screen renders

The editor shows a tree of message components on the left. Selecting a row unfolds an inspector under it with that component's settings: text fields, a markdown toolbar, colour and emoji pickers, plugin options. There is one inspector for each kind of component, and together they were a large share of the main chunk.

On load, no row is selected. Not one line of inspector code can run until the user clicks something. It was in the boot bundle only because the tree component imported it at the top of the file.

All the inspectors are now one lazy chunk behind a single entry module:

const LazyInspector = lazy(() => import("./inspectorPanels"));

function TreeRow({ node, selected }) {
  return (
    <li>
      <RowHeader node={node} />
      {selected && (
        <ChunkErrorBoundary onDismiss={deselect}>
          <Suspense fallback={<InspectorSkeleton />}>
            <LazyInspector node={node} />
          </Suspense>
        </ChunkErrorBoundary>
      )}
    </li>
  );
}

Two things make this invisible to the user:

  • Warm it when idle. Once the tree has mounted, an idle callback starts the import(). By the time a person has read the screen and clicked a row, the chunk is almost always already in memory. The lazy boundary delays the download past first paint. It doesn't delay the click.
  • Handle the load failing. A lazily loaded chunk can fail to arrive, for example when a deploy has replaced the files an open tab still refers to. The boundary around it offers a refresh, dismissing that notice deselects the row, and the rest of the editor keeps working throughout. I wrote about that failure in When a deploy deletes the chunk an open tab still needs.

One chunk for all inspectors is deliberate. A chunk per inspector type would save a little download for someone who only ever edits text, and cost a visible delay the first time each new type is opened.

Rule two: a module lands in one chunk, whole

The second saving came from something I had misunderstood about bundlers. I assumed that if a lazy dialog was the only user of a function, the function would end up in the dialog's chunk. It doesn't work that way.

Rollup (which Vite uses for production builds) removes exports that nothing uses. But an export that something uses has to live somewhere, and the unit of placement is the module, not the function. If a module is imported by the boot path at all, the whole module goes into a boot chunk, including every export that only lazy code calls.

My webhook module was a typical example. It exported a small URL parser, which the boot path used to recognise a pasted webhook address, and next to it all the code that sends, edits and fetches messages, which only the Send dialog used. One import of the parser put the entire sender in the boot bundle.

The fix is not clever. Split the file along the line between "needed at boot" and "needed later":

// before: one module, imported by boot code for parseWebhookUrl only
webhook/index.ts        parseWebhookUrl, sendMessage, editMessage, fetchMessage …

// after
webhook/webhookUrl.ts   parseWebhookUrl              ← boot imports this
webhook/send.ts         sendMessage, editMessage …   ← only the dialog imports this

I made the same cut in half a dozen places: the open/closed flag of the assistant panel apart from the assistant's logic, the toolbar's icons apart from the full icon set, the API calls a dialog makes apart from the types the rest of the app shares.

Barrel files undo all of it

A barrel is an index.ts that re-exports everything in a folder so callers can write one tidy import. Splitting the webhook module achieves nothing if boot code still imports the parser through the folder's barrel, because importing the barrel imports every module it re-exports, the sender included.

In theory a bundler can skip re-exported modules that have no side effects. In practice that depends on package flags and on what each module does at its top level, and I didn't want my first-load size to rest on it. The rule in this codebase is plain: code on the boot path imports from the specific file, never from a barrel.

Finding the modules worth splitting

Bundle visualisers show which modules are big. They don't show which ones are in the wrong chunk. For that I print, for each output chunk, the modules inside it and their size after tree-shaking. A tiny plugin does it:

// vite.config.ts
function chunkReport() {
  return {
    name: "chunk-report",
    generateBundle(_options, bundle) {
      for (const chunk of Object.values(bundle)) {
        if (chunk.type !== "chunk") continue;
        const kind = chunk.isEntry ? "entry" : chunk.isDynamicEntry ? "lazy" : "shared";
        console.log(chunk.fileName, kind);
        const modules = Object.entries(chunk.modules)
          .sort((a, b) => b[1].renderedLength - a[1].renderedLength);
        for (const [id, info] of modules) {
          console.log("   ", String(info.renderedLength).padStart(7), id);
        }
      }
    },
  };
}

Then I read the list for the chunks a first visit loads and ask one question of each large module: does the first screen call this? Modules where the honest answer is "one small function of it" are the candidates. The list was shorter than I expected, and each split was a few minutes of moving code between files.

Three cautions

Splitting can add requests. I once imported a few state modules directly from the app's top-level error screen, which lives in the entry chunk. The bundler responded by pulling those modules out of the main app chunk into chunks of their own, so both could share them. The build came out at 19 critical requests against a cap of 16, and 12 KB heavier. If code in the entry chunk needs something from the app, it should reach it through a dynamic import of the app chunk, not around it.

Imports can have side effects. The default entry point of Stripe's JavaScript package injects Stripe's script tag into the page as a side effect of being imported. Because it sat in a shared vendor chunk, every visitor on every page view loaded a payment script, with its cookies, though almost none of them would ever open the checkout. The package ships a second entry point, @stripe/stripe-js/pure, that does nothing until you call it. Check what your dependencies do at import time.

Enforce the result. The build measures the critical bundle from its own manifest and fails over budget, and it also caps the number of critical requests. Without that check, the next convenient top-level import quietly puts everything back.

Summary

  • Ask what the first screen actually renders. Anything that needs a click to appear can load after first paint, warmed during idle time.
  • A module is placed in one chunk as a whole. One boot-side import carries all of its exports along.
  • Split modules along the boot/later line, and import boot code from specific files, not barrels.
  • Print each chunk's modules to find the ones in the wrong place.
  • Watch the request count as well as the bytes, and fail the build on both.