Typescript dynamic import

1.6k Views Asked by At

With the current, latest version of TS (v2.5.x) it is possible to do dynamically import a module using a variable instead of hard coding it?

For example:

let modName: string = "myModule";
const myMod = await import(modName);

When I use a variable, I get an error "Cannot find module '.'". It looks like the TS is transpiling it to that line of code when I use a variable, so it is irrelevant what I set that variable to.

I have looked at these relevant threads:

Dynamically import module in TypeScript TypeScript ES dynamic `import()`

1

There are 1 best solutions below

0
On

You can use eval.

function body(theModule:any){
   // do something with the module
}

var moduleName = 'name-of-your-module';
eval (`import('${moduleName}').then(body)`);