Mastering Webpack Code Splitting: From Entry Points to Magic Comments

This article explains how to use Webpack's code splitting techniques—including multiple entry points, the SplitChunksPlugin, dynamic imports, and magic comments—to break large bundles into smaller chunks, reduce duplicate dependencies, and improve loading performance in modern frontend applications.

WeDoctor Frontend Technology
WeDoctor Frontend Technology
WeDoctor Frontend Technology
Mastering Webpack Code Splitting: From Entry Points to Magic Comments

1. Introduction

By default, Webpack bundles all code into a single chunk. For large single‑page applications this can produce a massive bundle, so developers often split each route into its own chunk to enable on‑demand loading.

Code splitting is one of Webpack's most notable features. It allows you to separate code into different bundles, load them on demand or in parallel, reduce bundle size, and control resource‑loading priority, which can dramatically improve load times when used wisely.

2. About Code Splitting

Consider two simple files:

index.js

import { mul } from './test'
import $ from 'jquery'

console.log($)
console.log(mul(2, 3))

test.js

import $ from 'jquery'

console.log($)

function mul(a, b) {
  return a * b
}
export { mul }

Both files depend on jquery, so a default build produces a single main bundle of about 324 KB.

1. Multiple Entry Points

Webpack's entry can be an object, allowing index and test to be separate entry points:

entry: {
  index: './src/index.js',
  test: './src/test.js'
},
output: {
  filename: '[name].[hash:8].js',
  path: path.resolve(__dirname, './dist')
},

The build now creates two files, but each still contains the ~320 KB of jquery because the dependency is duplicated across the two entry chunks.

Issue: duplicate modules are bundled into every entry chunk, leading to larger files and reduced flexibility.

If entry chunks share modules, those modules are duplicated in each bundle.

This approach lacks flexibility and cannot dynamically extract core application logic.

We need a method that extracts shared dependencies without manually configuring multiple entries.

2. SplitChunksPlugin

Webpack 5 ships with the built‑in SplitChunks plugin, which replaces the older CommonsChunkPlugin. Adding a simple configuration splits shared modules automatically:

entry: './src/index.js', // single entry again
optimization: {
  splitChunks: {
    chunks: 'all'
  }
},

The resulting build shows an additional chunk named something like vendors-node_modules_jquery_dist_jquery_js.xxxxx.js, containing the extracted jquery module.

Default splitChunks options (excerpt):

splitChunks: {
  chunks: 'async',
  minSize: 20000,
  minRemainingSize: 0,
  minChunks: 1,
  maxAsyncRequests: 30,
  maxInitialRequests: 30,
  enforceSizeThreshold: 50000,
  cacheGroups: {
    defaultVendors: {
      test: /[\\/]node_modules[\\/]/,
      priority: -10,
      reuseExistingChunk: true
    },
    default: {
      minChunks: 2,
      priority: -20,
      reuseExistingChunk: true
    }
  }
}

The cacheGroups setting determines how modules are assigned to vendor or default groups. You can customize the generated filename via splitChunks.name, either as a boolean, a function, or a static string.

3. Dynamic import()

Using the import() syntax creates a separate chunk automatically:

// index.js
import $ from 'jquery'
import('./test').then(({ mul }) => {
  console.log(mul(2, 3))
})
console.log($)

The build produces a distinct chunk for test.js:

Dynamic imports can also include expressions, enabling theme‑based lazy loading:

const themeType = getUserTheme()
import(`./themes/${themeType}`).then(module => {
  // apply theme
})

4. Magic Comments

Magic comments let you control the generated chunk name and loading behavior:

import(/* webpackChunkName: "my-chunk-name" */ './test')

Prefetch and preload comments affect when the chunk is fetched:

// Prefetch (load when browser is idle)
import(/* webpackPrefetch: true */ './test')

// Preload (load immediately in parallel with parent chunk)
import(/* webpackPreload: true */ './test')

Key differences:

Preload chunks start downloading as soon as the parent chunk loads, with medium priority.

Prefetch chunks begin after the parent chunk finishes, downloading only when the browser is idle.

3. Conclusion

Initially, bundling everything into one file reduces HTTP requests, but as projects grow, large initial payloads hurt user experience. Code splitting—through multiple entries, SplitChunksPlugin, dynamic imports, and magic comments—offers flexible ways to shrink initial bundles and improve performance.

References

How to use SplitChunks for fine‑grained code splitting

Code Splitting – Webpack

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

FrontendOptimizationJavaScriptWebpackcode-splitting
WeDoctor Frontend Technology
Written by

WeDoctor Frontend Technology

Official WeDoctor Group frontend public account, sharing original tech articles, events, job postings, and occasional daily updates from our tech team.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.