简体   繁体   中英

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?

This is what we have and it's failing with a 404 error (1.1.bundle.js not found)

This is what webpack.config looks like:

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 . However, I never created 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. So it seems that webpack cannot handle this.

By default, webpack tries to bundle all the code in a single file. 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.

Webpack handles this situation by using CommonsChunkPlugin , your config must look like this:

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. In your case, dynamicFileName = 'related_files' , not file1/file2.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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