Dynamic System.import with webpack?

warpdesign picture warpdesign · Mar 19, 2016 · Viewed 19.8k times · Source

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

I didn't have any problem porting most of the code.

However, I have some code that needs to dynamically load an ES6 module, like this:

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

src is an external ES6 module which may also have dependencies (static imports).

How could I port this code to Webpack ? If I try to use require statement I'm getting a WARNING which seems to be normal according to the Webpack docs.

Answer

sic1 picture sic1 · Jan 6, 2017

The previous answers were correct, but now in webpack 2.2 + babel (as of writing, v2.2.0-rc.3 is the latest version) we can do this. I have not tested myself, but just did the research that lead me here as well.

Read this from the webpack documentation: Code Splitting with es2015

Just below that section is Dynamic Expressions with this example:

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

Be sure to note you will need to install the Syntax Dynamic Import plugin, as the doc mentions.