jktravis
jktravis

Reputation: 1568

How can I code split a single module to be shared between multple entry points in webpack?

I have an very large, older MVC application where we've started using webpack for some of our TS/JS. I've tried to implement code-splitting in the past, but the resulting modules were huge and awkwardly named. The whole thing was very confusing. We ultimately had to roll it back due to some compatibility issues we had with older browsers.

We're moving towards doing more in React, and we want to avoid duplicating the React library throughout the application, but we're not quite ready to move to a full-on SPA just yet. Instead, we are currently "splitting" the application at the routes using a ton of entry point files (44 currently.)

Is it possible to extract just the React and React-DOM modules into a standalone? I presume we'd still need to import it where we're using it so that the type-linting won't freak out.

Or do we add React to the page the old-school way, and squelch those warnings and errors?

TLDR: How can I code-split just React itself out when using multiple entry points?

Upvotes: 1

Views: 1663

Answers (1)

James South
James South

Reputation: 604

this ought to work:

https://webpack.js.org/guides/code-splitting/#prevent-duplication

 optimization: {
     splitChunks: {
       chunks: 'all'
    }
   }

I've never used so many entry points but add this to your webpack config, it should out of the box extract react into a chunk called vendors~main(long hash).js. at the bottom of that page are analysis tools, you can check your bundle for any leftover duplication.

edit to add: this is even better:

https://webpack.js.org/plugins/split-chunks-plugin/#split-chunks-example-3

module.exports = {
  //...
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
          name: 'vendor',
          chunks: 'all',
        }
      }
    }
  }
};

Upvotes: 2

Related Questions