Search code examples
gitreactjswebpackbundlecommonschunkplugin

How to use one vendor chunk file (webpack) for multiple react projects


I have different gits with different react applications. Where every application should use the same vendors chunk file with external packages (React, ReactDOM ...)

Projects setup:

Project 1 (git)
   /dist/...
   /src/...
   webpack.config.js
Project 2 (git)
   /dist/...
   /src/...
   webpack.config.js
Project N (git)
   ...

Every webpack.config.js contains this configuration but with different Library name:

module.exports = {
  entry: {
      app: './src/App.ts',
      vendor: ['react', 'react-dom', 'react-redux', 'redux', 'redux-thunk']
  },
  output: {
      path: path.resolve(__dirname, "dist"),
      filename: '<Name>.bundle.js',
      library: "<Name>",
      libraryTarget: "umd"
  },
  module: { /* ... */ },
  plugins: [
      new webpack.optimize.CommonsChunkPlugin({
          name: 'vendor',
          filename: 'vendor.bundle.js'
      })
  ]
}

Problem:

Webpack builds a vendor.bundle.js especially for the current library/project, not for global use, is there an option for webpack creating a vendor.bundle.js which can be included on a single page where both applications can be loaded based on this file:

Example:

<html>
   <head>
      <script src="/vendor.bundle.js"></script>
   </head>
   <body>
      <script src="/app1.bundle.js"></script>
      <script src="/app2.bundle.js"></script>
   </body>
</html>

Solution

  • You can use the DllPlugin. You would need an additional Webpack configuration file, let's say webpack.vendor.config.js with the common dependencies, for example: 'react', 'react-dom', 'react-redux', 'redux', 'redux-thunk'. This bundle would be completely decoupled from the rest of the projects.

    Once you have this working, it will create a manifest.json that can be used from your different projects, so no need to use the webpack.optimize.CommonsChunkPlugin plugin, but the DllReferencePlugin instead.

    With this approach, your different project's bundle files will be smaller, which means shorter build and rebuild times.