Dynamically import module in TypeScript

2019-02-23 19:11发布

What is the TypeScript way of loading modules dynamically (path to the module is known at runtime)? I tried this one:

var x = "someplace"
import a = module(x)

But it seems that TypeScript compiler would like to see path as a string in import/module at compile time:

$ tsc test.ts 
/tmp/test.ts(2,19): error TS1003: Identifier expected.
/tmp/test.ts(2,20): error TS1005: ';' expected.

I know I can for example directly use RequireJS (if I use amd module format), but that doesn't feel right to me - it's solution for one particular library.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-23 19:49

You need to specify a hard coded string. Variables will not work because that would mean code would have to exist outside the define call which typescript will generate for you. All your file code has to actually live "inside" this define call upon javascript generation. :)

However you could do it yourself if you do not use typescript AMD feature and just use requirejs.d.ts

查看更多
萌系小妹纸
3楼-- · 2019-02-23 20:02

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

import function is synchronised 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
}
查看更多
登录 后发表回答