In Webpack 1, we do code-splitting imports with require.ensure
, which can take an array of modules. These modules are combined into a single bundle and fetched with one HTTP request:
require.ensure(['module1', 'module2'], (require) => {
const module1 = require('module1');
const module2 = require('module2');
// use these modules here...
});
// ==> both modules are served as a single bundle, e.g. '5.js'
With Webpack 2, we can now use System.import
for a cleaner syntax... but it seems like System.import only accepts a single module to import. Fine -- I can use Promise.all
-- but then I end up with two bundles:
Promise.all([
System.import('module1'),
System.import('module2')
]).then( (module1, module2) => {
// use these modules here...
});
// ==> each module served as its own bundle, e.g. '5.js', '6.js'
Is there a way to use System.import
but still combine the requested modules into a single bundle?
(Yes, in some cases I can add a new module file that in turn imports and consumes both the dependencies, and that's often the best approach, but for several of my use cases it merely adds additional boilerplate)
According to Sean T. Larkin (webpack core team), using a single file that imports both resources is your best bet (like you already discovered).
//http://stackoverflow.com/a/36878745/402706
export {default as module1} from './modules/module1';
export {default as module2} from './modules/module2';
System.import('bundle').then({ module1, module2 } => {
// do stuff
}).catch(err => {
console.log("Chunk loading failed");
});
However, there's no disadvantage to using require.ensure
as you have it other than,
not being able to handle async load fails via a promise. src
He mentioned future changes that, "may help with this," but I didn't press for what those might be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With