Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consolidating Bundles in Webpack 2 with System.import

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)

like image 461
Benj Avatar asked Nov 20 '22 21:11

Benj


1 Answers

According to Sean T. Larkin (webpack core team), using a single file that imports both resources is your best bet (like you already discovered).

Example (untested)

bundle.js

//http://stackoverflow.com/a/36878745/402706
export {default as module1} from './modules/module1';
export {default as module2} from './modules/module2';

Import the single file

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.

like image 63
Brandon Boone Avatar answered Nov 22 '22 09:11

Brandon Boone