Search code examples
webpackwebpack-4webpack-splitchunks

How to know if Webpack's 4 splitChunks works?


I tried to add

  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  },

To my webpack config file but when I compare the network when loading the pack in incognito, with and without that config, both are identical.

Also running a build yield the same output.

Is there another way to know for sure if it does something?

What I want to achieve is that each page on my site will have its own chunk, and only that will be loaded when that page is navigated to.


Solution

  • Well, to separate each chunk per page, you should use "Dynamic import", which is a technique of code splitting. By using it, you explicitly say to webpack that you don't need it, up to the point that it is required.

    What it does? It is a "wrapper" that is turned into require.ensure, which returns a promise. And because it is a promise, it can be requested down the road.

    To do that, you: import("path/to/whatever");. If you want to do something, for example, in react.

    import("component").then((c) => return <c />);