使用System.import整合Webpack 2中的Bundles

时间:2016-08-19 15:18:19

标签: javascript webpack

在Webpack 1中,我们使用require.ensure进行代码拆分导入,可以使用一组模块。这些模块组合成一个捆绑包,并使用一个HTTP请求获取:

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'

使用Webpack 2,我们现在可以使用System.import来获得更清晰的语法......但似乎System.import只接受一个模块来导入。很好 - 我可以使用Promise.all - 然后我最终得到两个包:

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'

有没有办法使用System.import但仍然可以将所请求的模块合并到一个捆绑包中?

(是的,在某些情况下,我可以添加一个新的模块文件,然后导入并消耗两个依赖项,这通常是最好的方法,但对于我的一些用例,它只是增加了额外的样板)

2 个答案:

答案 0 :(得分:1)

According to Sean T. Larkin (webpack core team),使用导入两种资源的单个文件是您最好的选择(就像您已经发现的那样)。

示例(未经测试)

bundle.js

//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");
});

但是,除了

之外,使用require.ensure没有任何不利之处
  

无法通过承诺处理异步加载失败。 src

他提到了未来的变化,“may help with this”,但我没有强调那些可能是什么。

答案 1 :(得分:-1)

我希望答案可以帮助你...... 我有同样的问题来做动态模块加载并且认为将app文件夹组合为webpack 2的根上下文和Ignore插件是因为我不理解ContextReplacementPlugin。但是这项工作并没有将所有内容捆绑在一个文件中。

以下是片段:

import angular from 'angular';

var paths = ["components/app.components.js", "shared/app.shared.js"];

Promise.all(paths.map(path => System.import('../app/' + path))).then(modules => {
    let dependencies = [];
    modules.forEach(module => {
        dependencies.push(module.default.name);
    })
    angular.module("app", dependencies);
    angular.bootstrap(document, ['app']);
}).catch(error => {
    console.error(error.message)
});

使用此结构,您可以获取api,然后将其用于动态加载,例如。

然后在webpack中我使用IgonorePlugin来避免来自webpack build的* .html文件:

  plugins: [
        new webpack.IgnorePlugin(/vertx/),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true
        }),
        new webpack.IgnorePlugin(/[A-Za-z]*\.(html)$/i)
    ],

这是项目github:https://github.com/yurikilian/angular1es6