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

7
  • Have you checked the transpiled code? How does it look? typescriptlang.org/play/… Commented Oct 4, 2017 at 23:07
  • 1
    Is it a typo that you declare modName but use mod on the next line? Commented Oct 4, 2017 at 23:08
  • This feature is all about working in tandem with your loader. You need a module loader for this to work. Commented Oct 5, 2017 at 5:52
  • Yes, it is a typo @zerkms Commented Oct 5, 2017 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")}) Commented Oct 5, 2017 at 20:01

1 Answer 1

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)`);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.