17

我刚刚意识到,如果您使用 动态加载模块require.ensure(),webpack 将不会一起分析和分块依赖项。这在某种程度上是有道理的,有人可能会争辩说,webpack 无法知道这些模块是否会被传输,但我们是否可以强制 webpack 完成这项工作?

示例是:

应用程序.js

require.ensure([ 'module1.js' ], ( require ) => {
    // at some point
    require( 'module1.js' );
}, 'Module1');

require.ensure([ 'module2.js' ], ( require ) => {
    // at some point
    require( 'module2.js' );
}, 'Module2');

模块1.js

let io = require( 'socket.io-client' );

模块2.js

let io = require( 'socket.io-client' );

这个编译的结果是,这两个模块都将整个 socket-io 库“链接”到它们的块中。我最初的期望是,CommonsChunkPlugin会抓住那些requires并将那个大库放入一个公共块中。

new webpack.optimize.CommonsChunkPlugin( 'common' ),

然而不起作用。当然,我总是可以手动“解决”这种依赖关系,但我希望 webpack 能以某种方式做到这一点?

4

2 回答 2

5

答案隐藏在配置中CommonsChunkPlugin

new webpack.optimize.CommonsChunkPlugin({
  name: 'main', // Important to use 'main' or not specify, since 'main' is default
  children: true, // Look for common dependencies in all children,
  minChunks: 2, // How many times a dependency must come up before being extracted
});

children: true是这个配置的主要部分。来自文档:

如果为 true,则公共块的所有子项都被选中


编辑异步公共块

如果要分块下载异步通用代码,则应更改上述配置并添加async: true

new webpack.optimize.CommonsChunkPlugin({
  name: 'main',
  children: true, 
  minChunks: 2, 
  async: true, // modification
});

来自关于的文档async

如果为 true,则创建一个新的异步公共块作为 options.name 的子级和 options.chunks 的兄弟级。它与 options.chunks 并行加载。可以通过提供所需的字符串而不是 true 来更改输出文件的名称。

现在创建了仅包含socket.io-client来自您的示例的附加块。这与webpack docs中的原始示例很接近。

于 2016-09-06T10:39:43.940 回答
0

So far I found one possible solution. If you use webpack's require.include() method to just include (not evaluate) the "shared library, here socket.io-client" also in the parent module, here app.js, the CommonChunkPlugin will now be able to sort things out correctly.

require.include( 'socket.io-client' ); // import io from 'socket.io-client'; also works
require.ensure([ 'module1.js' ], ( require ) => {
    // at some point
    require( 'module1.js' );
}, 'Module1');

require.ensure([ 'module2.js' ], ( require ) => {
    // at some point
    require( 'module2.js' );
}, 'Module2');

However, this doesn't seem right to me since this IS a manual resolving of dependencies, which is actually not what I want have to do using something like Webpack.

于 2016-09-06T09:57:36.797 回答