5

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.

4
  • @PHPglue ES6 modules are not exclusive to Node.js. They don't have in-browser semantics yet, but for-browser build systems are already using them. Commented Jun 10, 2016 at 22:03
  • Do you not know the class name or do you not know the path? Or both? Commented Jun 11, 2016 at 0:48
  • @PHPglue We're not using node, we're using Aurelia. Commented Jun 11, 2016 at 4:25
  • @FelixKling I know the path and the class name (always the same class name, just from a dynamic module/path). Commented Jun 11, 2016 at 4:26

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.