Search code examples
javascriptreactjswebpackwebpack-4bundles

How to extract React library to separate bundle?


Is it possible to extract React and(or) ReactDOM libraries to separate bundle via Webpack 4? For example I have the React app which includes React, ReactDOM and Moment.js packages. So I expect two bundles as the result:

  • react.js = react + react-dom
  • main.js = moment + app components

How to split bundles in depends of name of the packages but not of frequency of use in entry points?


Solution

  • Hi @VRSY after spending some time in understanding webpack's SplitChunksPlugins.js I figured it out how to write RegEx to extract node_modules in spearate vendor chunks.

    splitChunks: {
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
              name: 'vendor',
              chunks: 'all',
            }
          }
        }
    

    New chunk would be bigger than 30kb

    I was doing a mistake while writing a regex before for module folder name. But relative path regex is a good bet to match the regex.