Dynamically import module in TypeScript

ES proposal dynamic import is supported since TypeScript 2.4. Document is here.

import function is asynchronous and returns a Promise.

var x = 'someplace';
import(x).then((a) => {
  // `a` is imported and can be used here
});

Or using async/await:

async function run(x) {
  const a = await import(x);
  // `a` is imported and can be used here
}

You need to specify a hard coded string. Variables will not work.

Update

JavaScript now got dynamic imports. So you can do import(x) :https://developers.google.com/web/updates/2017/11/dynamic-import

TypeScript supports it as well. That said you would still want the argument to be statically analyzable for type safety e.g.

const x = 'someplace';
import(x).then((a) => { // TypeScript knows that `x` is 'someplace' and will infer the type of `a` correctly
});