在 TypeScript 中动态导入模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18118222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically import module in TypeScript
提问by Stan Prokop
What is the TypeScript way of loading modules dynamically (path to the module is known at runtime)? I tried this one:
动态加载模块的 TypeScript 方式是什么(模块的路径在运行时已知)?我试过这个:
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:
但似乎 TypeScript 编译器希望在编译时将路径视为导入/模块中的字符串:
$ 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.
我知道我可以例如直接使用 RequireJS(如果我使用 amd 模块格式),但这对我来说并不合适 - 它是一个特定库的解决方案。
回答by aleung
ES proposal dynamic importis supported since TypeScript 2.4. Document is here.
从 TypeScript 2.4 开始支持ES 提案动态导入。文件在这里。
import
function is asynchronous and returns a Promise
.
import
函数是异步的并返回一个Promise
.
var x = 'someplace';
import(x).then((a) => {
// `a` is imported and can be used here
});
Or using async/await
:
或使用async/await
:
async function run(x) {
const a = await import(x);
// `a` is imported and can be used here
}
回答by basarat
You need to specify a hard coded string. Variables will not work.
您需要指定一个硬编码字符串。变量将不起作用。
Update
更新
JavaScript now got dynamic imports. So you can do import(x)
:https://developers.google.com/web/updates/2017/11/dynamic-import
JavaScript 现在有了动态导入。所以你可以这样做import(x)
:https: //developers.google.com/web/updates/2017/11/dynamic-import
TypeScript supports it as well. That said you would still want the argument to be statically analyzable for type safety e.g.
TypeScript 也支持它。也就是说,您仍然希望参数可以静态分析以确保类型安全,例如
const x = 'someplace';
import(x).then((a) => { // TypeScript knows that `x` is 'someplace' and will infer the type of `a` correctly
});