Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript dynamic import

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()`

like image 717
Hari Avatar asked Oct 26 '25 14:10

Hari


1 Answers

You can use eval.

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

var moduleName = 'name-of-your-module';
eval (`import('${moduleName}').then(body)`);
like image 92
Bing Ren Avatar answered Oct 29 '25 06:10

Bing Ren