How does lazy module loading work in ES6
Asked Answered
S

3

26

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?

Sexcentenary answered 4/5, 2015 at 14:49 Comment(2)
You have to use the system loader API. See Dynamic module import in Ember CLIAam
No, it is not possible using import syntax. You can however use an asynchronous(!) equivalent of the require function.Eightieth
K
22

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();
        // ...
    })
}
Kell answered 5/5, 2015 at 9:23 Comment(2)
There is now a proposal for dynamic import from JavaScript: github.com/tc39/proposal-dynamic-import. It specifies a simple import() function on the global scope. WebPack 2 supports this sinve version v2.1.0-beta.28.Interception
Example for lazyloading jQuery in ES6 : import('jquery').then((jquery) => { // Because jquery is the module, here is the new syntax for using this window.$ = jquery.default; window.$('#id'); });Convene
C
6

Example for lazyloading jQuery in ES6 :

import('jquery').then((jquery) => {
     // Because jquery is the module, here is the new syntax for using this 
          window.$ = jquery.default;
          window.$('#id');
});
Convene answered 7/5, 2019 at 12:46 Comment(0)
D
3

This dynamic import functionality is now available as part of the ECMAScript specification - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import

Dorman answered 18/4, 2023 at 1:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.