gpt4 book ai didi

javascript - (Webpack) 如何分块动态模块依赖

转载 作者:可可西里 更新时间:2023-11-01 01:19:30 24 4
gpt4 key购买 nike

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

例子是:

app.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');

module1.js

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

module2.js

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

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

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

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

最佳答案

答案隐藏在 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 是这个配置的主要部分。来自文档:

If true all children of the commons chunk are selected


编辑异步公共(public) block

如果你想异步下载 block 中的公共(public)代码,你应该改变上面的配置,添加async: true

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

来自关于 async 的文档:

If true a new async commons chunk is created as child of options.name and sibling of options.chunks. It is loaded in parallel with options.chunks. It is possible to change the name of the output file by providing the desired string instead of true.

现在创建了仅包含示例中的 socket.io-client 的附加 block 。这接近于 webpack docs 中的原始示例.

关于javascript - (Webpack) 如何分块动态模块依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39272209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com