在TypeScript中动态导入模块 [英] Dynamically import module in TypeScript
问题描述
动态加载模块的TypeScript方式是什么(在运行时已知模块的路径)?我试过这个:
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)
但似乎TypeScript编译器希望在编译时将路径视为导入/模块中的字符串:
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.
我知道我可以直接使用RequireJS(如果我使用amd模块格式),但那不是对我来说是对的 - 这是一个特定库的解决方案。
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.
推荐答案
您需要指定一个硬编码字符串。变量将无法工作,因为这意味着代码必须存在于 define
调用之外,而这些调用将为您生成。你的所有文件代码必须实际生活在内部这个定义调用javascript生成。 :)
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. :)
但是,如果您不使用打字稿AMD功能并且只使用requirejs.d.ts
However you could do it yourself if you do not use typescript AMD feature and just use requirejs.d.ts
这篇关于在TypeScript中动态导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!