Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically import JavaScript module using ES6 syntax? [duplicate]

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.

like image 382
Josh M. Avatar asked Oct 19 '22 07:10

Josh M.


1 Answers

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)

like image 170
Eugene Avatar answered Oct 20 '22 23:10

Eugene