Search code examples
javascriptes6-modules

How to perform a “variable” ES6 import?


Is it possible to import something into a module providing a variable name while using ES6 import?

I.e. I want to import some module at a runtime depending on values provided in a config:

import something from './utils/' + variableName;

Note that I’m using Node.js, but answers must take compatibility with ECMAScript modules into consideration.


Solution

  • Not with the import statement. import and export are defined in such a way that they are statically analyzable, so they cannot depend on runtime information.

    You are looking for the loader API (polyfill), but I'm a bit unclear about the status of the specification:

    System.import('./utils/' + variableName).then(function(m) {
      console.log(m);
    });