4

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

Hari
  • 373
  • 3
  • 11
  • Have you checked the transpiled code? How does it look? https://www.typescriptlang.org/play/index.html#src=async%20function%20q()%20%7B%0D%0A%20%20%20%20let%20modName%3A%20string%20%3D%20%22myModule%22%3B%0D%0A%20%20%20%20const%20myMod%20%3D%20await%20import(modName)%3B%0D%0A%7D – zerkms Oct 04 '17 at 23:07
  • 1
    Is it a typo that you declare `modName` but use `mod` on the next line? – zerkms Oct 04 '17 at 23:08
  • This feature is all about working in tandem with your loader. You need a module loader for this to work. – Aluan Haddad Oct 05 '17 at 05:52
  • Yes, it is a typo @zerkms – Hari Oct 05 '17 at 19:50
  • The transpiled code looks like this: `Promise.resolve().then(function(){return!function(){var e=new Error('Cannot find module "."');throw e.code="MODULE_NOT_FOUND",e}()})`. I am using WebPack and Uglify, which is why the code looks like this. If I use a hardcoded string: `Promise.resolve().then(function(){return o("my-module-name")})` – Hari Oct 05 '17 at 20:01
  • Did you ever find a solution for this or is it simply not possible? – prawn May 24 '18 at 23:37
  • Sorry of the delay in response. No resolution on this. When you use a variable name, the transpiler has no clue what you want to load. I ended up putting the typescript in a file and used eval to evaluate it on demand. – Hari Jun 28 '18 at 00:17

1 Answers1

2

You can use eval.

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

var moduleName = 'name-of-your-module';
eval (`import('${moduleName}').then(body)`);
Bing Ren
  • 1,589
  • 17
  • 26