Is ES2015+, how can I dynamically import a module?
E.g. instead of...
import {SomeClass} from 'lib/whatever/some-class';
I don't know the path at runtime, so I want to I have the path stored in a variable, and I want to import a specific thing from that module:
function doDynamicStuff(path) {
let importedThing = ...; //import * as importedThing from path;
let thingIReallyWant = importedThing.someExportedVariable;
...
}
I'm not sure what syntax to use, or if it's possible to do this at all. I tried using let importedThing = require(path);
but we're not using RequireJS
.
ES2015 does not support dynamic imports by design.
In current JavaScript module systems, you have to execute the code in order to find out what the imports and exports are. That is the main reason why ECMAScript 6 breaks with those systems: by building the module system into the language, you can syntactically enforce a static module structure.
...
A module’s structure being static means that you can determine imports and exports at compile time (statically) – you only have to look at the source code, you don’t have to execute it.
From ECMAScript 6 modules: the final syntax
To dynamically import module you have to explicitly use module loaders (like RequireJS or SystemJS)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With