Search code examples
javascriptimportmodulelazy-loadingecmascript-6

How does lazy module loading work in ES6


How can I lazily-load ES6 modules? By lazy, I mean I don't want to actually load modules that aren't needed. For example, here's something I can do with RequireJS:

function someEventHandler() {
    var SomeModule = require('some-module'),
        module = new SomeModule();
    // ...
}

Something along the same lines doesn't appear to be possible using ES6 imports:

// Doesn't appear to be valid...
function someEventHandler() {
    import SomeModule from 'some-module';
    var module = new SomeModule();
    // ...
}

Are there any viable techniques to only pull in dependencies when needed, using ES6 modules? Or is the only path to trace the full dependency graph and fetch everything up-front?


Solution

  • The import statement will only work in the very top of files, and it will load all of them. This is mainly to avoid potential issues with circular dependencies.

    There will also be a way to do asynchronous loading; however the specification doesn't seem to be finalized yet. The ES6 module loader polyfill package uses a method called System.import(moduleName) that returns a promise and the final specification is likely to look similar:

    function someEventHandler() {
        System.import('some-module').then((SomeModule) => {
            var module = new SomeModule();
            // ...
        })
    }