简体   繁体   English

在webpack中动态加载块?

[英]Dynamically load chunks in webpack?

We load files dynamically ie, we don't know which files will be loaded until runtime. 我们动态加载文件,即我们不知道哪些文件将在运行时加载。 At the same, for faster loading, we'd like to put related files in the same chunk. 同时,为了加快加载速度,我们希望将相关文件放在同一个块中。

How can I do that with webpack? 我怎么能用webpack做到这一点?

This is what we have and it's failing with a 404 error (1.1.bundle.js not found) 这就是我们所拥有的,它失败了404错误(找不到1.1.bundle.js)

This is what webpack.config looks like: 这就是webpack.config的样子:

entry: {
   main: //...,
   related_files: [ //should create chunk for file1 and file2?
     './file1.js',
     './file2.js'
   ]
},

This is what the code to dynamically load the files looks like: 这是动态加载文件的代码如下所示:

var dynamicFileName = //...

require.ensure([], function (require) {
  //should dynamically load the chunk containing dynamicFileName? 
  //fails with 'file1.js' or 'file2.js' 
  var modImpl = require(dynamicFileName);
  //...
});

Update 1: the error message is caused by not configuring output.publicPath . 更新1:错误消息是由未配置output.publicPath引起的。 However, I never created 1.1.bundle.js . 但是,我从未创建过1.1.bundle.js It seems to be ignoring the entry point. 它似乎忽略了切入点。

Update 2: even after fixing output.publicPath , it's unable to load a dynamically generated filename. 更新2:即使在修复output.publicPath ,它也无法加载动态生成的文件名。 So it seems that webpack cannot handle this. 所以似乎webpack无法处理这个问题。

By default, webpack tries to bundle all the code in a single file. 默认情况下,webpack尝试将所有代码捆绑在一个文件中。 If you're using code from file1.js/file2.js in main entry point, webpack will bundle contents of all the files in main.js , and second entry point related_files will output only file1/file2 contents. 如果您使用从file1.js / file2.js代码main切入点,将的WebPack捆绑的所有文件的内容在main.js ,和第二个入口点related_files都只输出文件1 /文件2的内容。

Webpack handles this situation by using CommonsChunkPlugin , your config must look like this: 的WebPack通过处理这种情况CommonsChunkPlugin ,你的配置一定是这样的:

entry: {
   main: //...,
   related_files: ['./file1.js','./file2.js']
},
plugins: [
   new webpack.optimize.CommonsChunkPlugin('related_files', 'related_files.js')
]

Second part of the question is that webpack parses require statement, and outputs 1.1.bundle.js - the dynamic module, that can be loaded with require in the code. 问题的第二部分是webpack解析require语句,并输出1.1.bundle.js - 动态模块,可以在代码中加载require。 In your case, dynamicFileName = 'related_files' , not file1/file2. 在您的情况下, dynamicFileName = 'related_files' ,而不是file1 / file2。

Please see http://webpack.github.io/docs/code-splitting.html#split-app-and-vendor-code 请参阅http://webpack.github.io/docs/code-splitting.html#split-app-and-vendor-code

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

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