Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  185] [ 1]  / answers: 1 / hits: 26696  / 9 Years ago, mon, may 4, 2015, 12:00:00

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?


More From » import

 Answers
16

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();
// ...
})
}

[#66756] Saturday, May 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ramiro

Total Points: 431
Total Questions: 96
Total Answers: 105

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
ramiro questions
Thu, May 7, 20, 00:00, 4 Years ago
Tue, Apr 28, 20, 00:00, 4 Years ago
Sun, Feb 16, 20, 00:00, 4 Years ago
;