Search code examples
javascriptnpmwebpackwebpack-2

How to bundle npm packages with webpack and expose as an object?


I'm not actually sure this is possible, but what I'm trying to do is take a number of NPM packages, bundle them together using Webpack and expose them as an object where each package is a property.

For example, if I wanted react and react-dom bundled, it would then provide an object like:

{
    'react': /* react code */,
    'react-dom': /* react-dom code */
}

My current configuration is:

module.exports = {
  entry: [ 'react', 'react-dom' ],
  output: {
    path: __dirname + '/public',
    publicPath: 'http://localhost:8081/public/',
    filename: 'bundle.js',
    libraryTarget: 'umd',
  }
};

This seems to somewhat work in the fact that it does return an object, but the object it returns is whatever the last entry package is, so in this case, the object contains all of react-dom's methods.

If I were to change the order of the entry array to [ 'react-dom', 'react' ], then only the react methods would be exposed.

The idea would be to export the object so I can access both package methods using their properties like react.Component or react.PureComponent

I've also tried using the expose-loader, but that yields the same results as above, unless I configured it incorrectly.

Any ideas on how to properly configure webpack to achieve this?


Solution

  • If I understand correctly what you want to do, you could just set up a, let's say, bundle-source.js with this structure:

    exports.react = require('react');
    exports['react-dom'] = require('react-dom');
    exports.anyModule = require('anyModule');
    

    Then you set that bundle-source.js as the entry point of your webpack conf:

    module.exports = {
      entry: [ '...path-to...bundle-source.js' ],
      output: {
        path: __dirname + '/public',
        publicPath: 'http://localhost:8081/public/',
        filename: 'bundle.js',
        libraryTarget: 'umd',
      }
    };