简体   繁体   中英

Webpack split code with dynamic imports

I have an application that uses Webpack and now I want to do the following:

There is a folder with several resources:

resources
 ├── A.json
 ├── B.json
 └── C.json

I would like to load one of them dynamically:

function getResource(name, callback) {
    require(['./resources' + name + '.json'], function(resource) {
        callback(resource);
    });
}

That works fine for me, expect that all my resources bundled into the single 1.js file, but I'd like to split them and load only one on demand.

How can I do it with webpack?

Have you looked at webpack's code splitting ? The syntax require.ensure('foo.js', function() { ... }) will cause webpack to build foo.js into a separate file at compile time, and will load it on demand (via AJAX/JSONP) at runtime.

Dynamic requires are kind of an anti-pattern in webpack, though, and require.ensure only accepts static values for the module (not expressions). An easy way to get the behavior would be to set up static require.ensure calls in a switch statement, or if/elses, or something similar:

switch (someFlagYouSet) {
  case 'a':
    require.ensure('./resources/A.json', function() {...})
    break;
  case 'b':
    require.ensure('./resources/B.json', function() {...})
    break;
  ...
}

Maybe not as graceful as one would like, but dynamic requires don't really work well with static analysis and asset generation, so you get used to it. You still get your on-demand loading at runtime.

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