简体   繁体   English

如何将npm软件包与webpack捆绑在一起并作为对象公开?

[英]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. 我实际上不确定这是否可行,但是我想做的是获取许多NPM软件包,使用Webpack将它们捆绑在一起,并将它们作为对象公开,其中每个软件包都是一个属性。

For example, if I wanted react and react-dom bundled, it would then provide an object like: 例如,如果我想将reactreact-dom捆绑在一起,它将提供一个类似于以下内容的对象:

{
    '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. 这似乎在某种程度上确实起作用,因为它确实返回了一个对象,但是它返回的对象是最后一个entry包所具有的,所以在这种情况下,该对象包含了react-dom的所有方法。

If I were to change the order of the entry array to [ 'react-dom', 'react' ] , then only the react methods would be exposed. 如果我将entry数组的顺序更改为[ 'react-dom', 'react' ] ,则仅会公开react方法。

The idea would be to export the object so I can access both package methods using their properties like react.Component or react.PureComponent 这个想法是导出对象,这样我就可以使用它们的属性(例如react.Componentreact.PureComponent访问这两种包装方法。

I've also tried using the expose-loader , but that yields the same results as above, unless I configured it incorrectly. 我也尝试过使用expose-loader ,但是除非我配置不正确,否则产生的结果与上述相同。

Any ideas on how to properly configure webpack to achieve this? 关于如何正确配置webpack来实现此目标的任何想法?

If I understand correctly what you want to do, you could just set up a, let's say, bundle-source.js with this structure: 如果我正确理解了您想要做什么,则可以使用以下结构设置一个bundle-source.js

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: 然后,将bundle-source.js source.js设置为webpack conf的入口点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM