Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Code Splitting and Lazy Loading

The SplitChunksPlugin

Configure webpack optimization.splitChunks: chunks, minSize, minChunks, cacheGroups for vendor code, naming, runtimeChunk, and how to avoid too many requests.

Entry points and import() decide where chunks begin. The SplitChunksPlugin decides how to reorganize them afterwards: it finds modules that appear in several chunks, or that come from node_modules, and extracts them into their own chunk files. It ships with webpack 5 and is configured through optimization.splitChunks. You rarely need to enable it, but you will often want to tune it.

This lesson shows the options that matter, how a cache group works, and how to choose a strategy for vendor code. It assumes you know what a chunk is.

Webpack cannot run on this site. Config is shown read-only, and the runnable stand-in below implements a simplified version of the splitting rules so you can see how the numbers interact. Real webpack uses more criteria and different internals.

The defaults

Without any settings, production builds use roughly this:

JavaScript
optimization: {
  splitChunks: {
    chunks: 'async',          // only chunks loaded on demand
    minSize: 20000,           // 20 KB, a new chunk must be at least this big
    minChunks: 1,             // used by at least this many chunks
    maxAsyncRequests: 30,     // parallel requests for an on-demand load
    maxInitialRequests: 30,   // parallel requests at an entry
    cacheGroups: {
      defaultVendors: { test: /[\\/]node_modules[\\/]/, priority: -10, reuseExistingChunk: true },
      default: { minChunks: 2, priority: -20, reuseExistingChunk: true },
    },
  },
}

With chunks: 'async' the plugin leaves your initial (entry) chunk alone. The most common change is chunks: 'all', which also splits code that is needed at start-up, so vendor code can be cached separately from your app code.

The options that matter

Option Meaning
chunks 'async', 'initial' or 'all': which chunks may be split. A function lets you exclude some.
minSize Smallest size (bytes, before minification) of a chunk worth creating.
minChunks A module must be shared by at least this many chunks.
maxSize Hint to split big chunks further. Use sparingly: it can cause churn in file names.
name Fixed name. Setting it merges every matching module into one chunk.
cacheGroups Named rules: what to match and how to group it.
priority When a module fits several groups, the highest priority wins.
enforce Ignore size limits for this group.

Cache groups

A cache group is a rule: test selects modules (by path regex or function), and the group's other options say how to chunk the matches. The default defaultVendors group collects all of node_modules. A common customization separates a rarely changing framework from the other packages so that updating a small library does not invalidate the whole vendor file.

JavaScript
optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      framework: {
        test: /[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/,
        name: 'framework',
        priority: 40,
        enforce: true,
      },
      vendors: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        priority: 10,
      },
      shared: {
        minChunks: 2,
        priority: 5,
        reuseExistingChunk: true,
      },
    },
  },
}

The framework group has the highest priority, so React files go there; remaining dependencies go to vendors; anything else used by two or more chunks goes to shared.

A stand-in splitter

This runnable stand-in applies test, priority and minChunks to a list of modules, in the spirit of the plugin. It ignores the real size accounting and many details.

Node.js Stand-in: simplified cache groups

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.

format-date.js is only 1.5 KB. It reaches the shared chunk only because the group as a whole (31.5 KB with the button) clears minSize. A lone tiny helper would stay inside the chunks that use it, which is why small shared files are not split by default.

runtimeChunk

Webpack's runtime (the code that loads chunks) is small but changes whenever the chunk list changes. If it lives in your entry chunk, every build changes that file's hash. Setting runtimeChunk: 'single' moves it into its own file:

JavaScript
optimization: {
  runtimeChunk: 'single',
}

Now the entry file only changes when your code does. The lesson on long-term caching explains why that matters.

Practical strategies

  1. Start with chunks: 'all' and the defaults. Measure with a bundle analyzer before tuning anything.
  2. Separate the framework. React or Vue and their companions change on upgrades only, so a stable framework chunk is cached for months.
  3. Do not fight the request limits. If you create dozens of groups you reach maxInitialRequests. More files are not always faster.
  4. Avoid giant vendors chunks. One 1 MB vendor file is invalidated by any dependency update. Splitting by package works, but too fine-grained naming (one chunk per npm package) adds requests.
  5. Name chunks deterministically. Use moduleIds: 'deterministic' so ids do not shift when you add modules.

A quick check with a second stand-in

The next block calculates the downloaded weight for a first visit and a return visit after changing only app code, with and without a stable vendor chunk.

Node.js Stand-in: what does a returning visitor re-download?

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does chunks: 'all' change compared with the default 'async'?

    async limits splitting to dynamically loaded chunks. all also lets vendor and shared code leave the entry chunk.
  2. 2. A module matches two cache groups. Which one is used?

    priority resolves conflicts: the highest number wins.
  3. 3. Why use runtimeChunk: 'single'?

    The runtime changes when chunk lists change. A separate runtime file keeps the entry and vendor chunks cacheable.
  4. 4. Why might a tiny shared helper not be extracted into its own chunk?

    A new chunk must be at least minSize (20 KB by default in production) unless the group uses enforce.

Summary

  • SplitChunksPlugin extracts shared and vendor modules into their own chunks.
  • chunks: 'all', minSize, minChunks and cacheGroups are the key knobs; priority resolves overlaps.
  • Separate rarely changing framework code from frequently changing code.
  • runtimeChunk: 'single' stabilizes entry file hashes.
  • Measure first: more chunks are not automatically faster.

Next: Production Mode and Minification