Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Code Splitting and Lazy Loading

Code Splitting

Learn webpack code splitting: why one giant bundle hurts, how entry points, dynamic import() and splitChunks create chunks, and how to read the chunk graph.

By default a webpack build walks the import graph from your entry file and puts everything it finds into one output file. That is simple, but it means a visitor who only wants your landing page downloads the code for the admin panel, the chart library and the settings screen as well. Code splitting is the family of techniques that cut the bundle into several smaller files called chunks, so the browser loads only what the current page needs and can cache the rest.

This lesson explains the three ways webpack creates chunks, how to read the result, and how to think about the trade-off. The next two lessons go deeper into dynamic imports and the SplitChunksPlugin.

Webpack cannot run on this site, so the webpack configs below are read-only. The runnable examples are small Node.js stand-ins that reproduce the idea (a dependency graph and a chunking step) so you can experiment with the logic. They are labelled as stand-ins, not real webpack output.

Why one bundle becomes a problem

A bundle has two costs: the time to download it, and the time the browser needs to parse and run it. Both grow with size, and both happen before the user sees anything interactive. Typical culprits are large libraries (a charting library can weigh more than the rest of your app), code for rarely visited routes, and features behind a login.

Splitting gives you three wins:

  • Less work on first load. Only the code for the first screen is downloaded and executed.
  • Better caching. Your own code changes every deploy, but a vendor library changes rarely. If they live in different chunks, returning visitors re-download only what changed.
  • Parallel downloads. Several small files can be fetched at the same time over HTTP/2.

The three ways to split

Webpack offers three mechanisms, and real projects usually mix them.

flowchart LR
  A["Entry points<br/>(several entry keys)"] --> D["Chunks on disk"]
  B["Dynamic import()<br/>(split on demand)"] --> D
  C["SplitChunksPlugin<br/>(extract shared code)"] --> D

The three mechanisms that create chunks.

1. Entry points

You can declare more than one entry. Each entry becomes its own chunk and its own output file.

JavaScript
// webpack.config.js (read-only example)
module.exports = {
  mode: 'production',
  entry: {
    home: './src/home.js',
    admin: './src/admin.js',
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist',
  },
};

This is the oldest and most manual way. Its weakness: if home.js and admin.js both import lodash, the library is copied into both files. Fixing that is the job of mechanism three.

2. Dynamic import()

When webpack sees import('./chart.js') as a function call (not the static import ... from statement), it creates a split point. Everything reachable only through that call goes into a separate chunk that is fetched when the line runs.

JavaScript
button.addEventListener('click', async () => {
  const { drawChart } = await import('./chart.js');
  drawChart(data);
});

No configuration is needed. This is the best tool for routes, modals and heavy optional features.

3. SplitChunksPlugin

Built into webpack 5 and enabled by default for on-demand chunks, this optimization looks at all chunks and extracts modules that are shared or that are large third-party code. You tune it with optimization.splitChunks.

JavaScript
module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'all', // also split code that is loaded at start-up
    },
  },
};

Reading the chunk graph

Webpack turns your modules into chunks, and chunks into files (plus metadata such as a runtime that knows how to load them). A module can appear in more than one chunk only if you let it; the splitter's goal is to place each module where it is needed with as little duplication as possible.

The stand-in below models a tiny dependency graph and groups modules by which entry points reach them. A module reached by several entries is a candidate for a shared chunk, which is exactly the reasoning splitChunks applies (with size and request-count limits added).

Node.js Stand-in: which entries reach which module?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Modules owned by both entries land in the "home + admin" chunk, which both pages would load. That is the shape of a shared chunk.

Splitting on demand with a real runtime idea

A dynamic import() returns a promise. At run time webpack's tiny loader downloads the chunk file, runs it once, and resolves the promise with the module's exports. A second call for the same chunk reuses the cached result. Node can do the same thing with import() of a data: URL, which makes a good stand-in for a chunk file.

Node.js Stand-in: load a chunk only when asked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the evaluation message prints only once, even though the function ran twice. Webpack behaves the same way: each chunk is downloaded and executed at most once.

When not to split

Splitting is not free. Every extra file is another request, and many tiny chunks can be slower than one medium chunk, especially on high-latency networks or without HTTP/2. Some rules of thumb:

  • Do not split code that every page needs. Keep it in the main chunk.
  • Avoid chunks of only a few kilobytes. splitChunks.minSize (default 20 KB in production) already prevents most of these.
  • Measure before and after. The lesson on bundle analysis shows how.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which syntax creates a split point that webpack turns into a separate, on-demand chunk?

    The function-call form import() returns a promise and marks a split point. The static import statement is part of the same chunk as its importer.
  2. 2. Two entry points both import the same large library and you do nothing else. What happens?

    Without splitChunks the shared module is duplicated in each entry's chunk. SplitChunksPlugin is what extracts shared code.
  3. 3. Which is NOT a benefit of code splitting?

    Splitting usually increases the number of requests. The gain comes from sending less code up front and caching better, not from fewer requests.
  4. 4. How many times is a lazy chunk evaluated if the same import() runs twice?

    Webpack's runtime keeps a cache of loaded chunks and modules, so the code runs once and later imports reuse it.

Summary

  • A chunk is a group of modules that is written to one or more output files.
  • You create chunks with multiple entry points, dynamic import(), and optimization.splitChunks.
  • Splitting cuts first-load size and improves caching, but too many tiny chunks can hurt.
  • A chunk is loaded and executed at most once per page.

Next: Dynamic Imports and Lazy Loading