Skip to content

Instantly share code, notes, and snippets.

@thomasboyt
Created March 10, 2016 01:12
Show Gist options
  • Save thomasboyt/e331ed26977e3333b620 to your computer and use it in GitHub Desktop.
Save thomasboyt/e331ed26977e3333b620 to your computer and use it in GitHub Desktop.
webpack vendor problem

Let's say I have a "main" app and a "widget" app in the same codebase, with some dependencies shared between them. My webpack config might look something like

module.exports = {
  entry: {
    app: './app/appEntry.js',
    widget: './app/widgetEntry.js',
  },
  output: {
    path: 'public/',
    filename: '[name].js'
  },
};

I want to ensure that:

  • node_modules/ imports in the app bundle go into an app.vendor.js
  • node_modules/ imports in the widget bundle go into widget.vendor.js

I don't want or need a third common bundle for includes in both app and widget - would prefer common includes are just duplicated in both vendor bundles.

In the past, I've used this trick to automatically pull node_modules bundles into a separate file:

function vendorModule(modulePath) {
  var vendorPaths = [
    path.resolve(cwd, 'node_modules')
  ];

  for (var i in vendorPaths) {
    if (modulePath.indexOf(vendorPaths[i]) === 0) {
      return true;
    }
  }

  return false;
}

module.exports = {
  // ...
  
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.bundle.js',
      minChunks: function(module) {
        return module.resource &&
               vendorModule(module.resource) &&
               /\.js$/.test(module.resource);
      }
    }),
  ]
}

This worked fine for a single bundle. However, now that I have multiple entry points, I don't want to require the widget app's index.html to import the vendor.bundle.js that contains dependencies not needed for the widgets app.

Is this possible to do this without manually specifying the modules in each vendor bundle, or do I need to use a separate Webpack config for each bundle?

@sokra
Copy link

sokra commented Mar 10, 2016

CommonsChunkPlugin has a chunks property.

  new webpack.optimize.CommonsChunkPlugin({
      name: 'app.vendor',
      filename: 'app.vendor.bundle.js',
      chunks: ["app"],
      minChunks: function(module) {
        return module.resource &&
               vendorModule(module.resource) &&
               /\.js$/.test(module.resource);
      }
    }),

@thomasboyt
Copy link
Author

👍 works perfectly! so embarrassed that I missed that option while researching, thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment