Max Koretskyi
Max Koretskyi

Reputation: 105449

Can webpack2 load modules dynamically like SystemJS

webpack1 didn't have the ability to load modules on demand like I can do it with SystemJS:

function a() {
    var moduleName = getDynamicModuleName();
    SystemJS.import(moduleName).then(function (m) {
        console.log(m);
    });
}

Based on this article it seems that webpack2 can do that as well, so I put up the following:

function a() {
    var moduleName = getDynamicModuleName();
    import(moduleName).then(function (m) {

    });
}

However, webpack created the bundle for moduleName and gave the warning:

3:4-22 Critical dependency: the request of a dependency is an expression

So this is not exactly dynamic, it's the way code splitting works. So does webpack2 support true dynamic loading like SystemJS?

Upvotes: 0

Views: 504

Answers (1)

Stefan Dragnev
Stefan Dragnev

Reputation: 14473

Webpack is a bundler, it's not a loader. It provides a number of loader-like functions like require and import so that bundled modules can interact with each other, but that's about it. What you're looking for is an actual loader.

One possibility is to use webpack's script-loader:

require(`script!${moduleUrl}`, function() { ... })

Another possibility is to use an actual loader independently of webpack, like, for example little-loader:

var load = require("little-loader"); load("http://example.com/foo.js", function (err) { // ... your code ... });

Upvotes: 1

Related Questions