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

Ben*_*enj 5 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'
Run Code Online (Sandbox Code Playgroud)

使用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'
Run Code Online (Sandbox Code Playgroud)

有没有办法使用System.import但仍然将所请求的模块组合成一个捆绑包?

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

小智 -1

我希望这个答案对您有所帮助...我在进行动态模块加载和存档时遇到了同样的问题,将应用程序文件夹组合为 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)
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

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