Dynamic System.import with webpack?

I am trying to port some ES6 code that I wrote that uses systemjs + Babel.

I had no problem porting most of the code.

However, I have some code that should dynamically load the ES6 module, for example:

function load(src) {
    System.import(src).then(function() {});
}

src is an external ES6 module that can also have dependencies (static import).

How can I port this code to webpack? If I try to use the require statement, I get a warning that seems normal according to the Webpack docs.

+4
source share
4 answers

, webpack 2.2 + babel ( , v2.2.0-rc.3 - ), . , , .

webpack: es2015

:

function route(path, query) {
  return import("./routes/" + path + "/route")
    .then(route => new route.Route(query));
}
// This creates a separate chunk for each possible route
Hide result

, Syntax Dynamic Import plugin, .

+8

Webpack 1 System.import, , Webpack require.ensure . : https://webpack.imtqy.com/docs/code-splitting.html#es6-modules

, , Webpack context, . https://webpack.imtqy.com/docs/context.html

Webpack 2 , ES6 System.import.

+3

, " " - ( ). , ( webpack), - require.ensure - . .

SystemJS webpack :

function load(moduleName) {
    switch (moduleName) {
        case 'foo':
            require.ensure([], require) => {
                const foo = require('./foo.js');
                // do something with it
            }
            break;
        case 'bar':
            require.ensure([], require) => {
                const bar = require('./bar.js');
                // do something with it
            }
            break;
    }
}

, require.ensure ( -).

+2

, little-loader, . :

var load = require('little-loader');

load('<src>', function(err) {
    // loaded now, do something
});
+1

All Articles