【问题标题】:Dynamically import module in TypeScript在 TypeScript 中动态导入模块
【发布时间】:2013-08-09 16:55:40
【问题描述】:

TypeScript 动态加载模块的方式是什么(模块的路径在运行时已知)?我试过这个:

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

但似乎 TypeScript 编译器希望在编译时将路径视为 import/module 中的字符串:

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

我知道我可以例如直接使用 RequireJS(如果我使用 amd 模块格式),但这对我来说感觉不对 - 它是针对特定库的解决方案。

【问题讨论】:

  • 使用 TypeScript 0.9.1 而不是 'module' 您现在需要使用 'require' 尝试将导入更改为: import a = require(x)
  • @hnuecke:你的意思是const a = require('x')

标签: import module typescript


【解决方案1】:

您需要指定一个硬编码字符串。变量将不起作用。

更新

JavaScript 现在有了动态导入。所以你可以做import(x):https://developers.google.com/web/updates/2017/11/dynamic-import

TypeScript 也支持它。也就是说,您仍然希望参数可以静态分析以实现类型安全,例如

const x = 'someplace';
import(x).then((a) => { // TypeScript knows that `x` is 'someplace' and will infer the type of `a` correctly
}); 

【讨论】:

    【解决方案2】:

    从 TypeScript 2.4 开始支持 ES 提案 dynamic import。文档是here

    import 函数是异步的,返回一个Promise

    var x = 'someplace';
    import(x).then((a) => {
      // `a` is imported and can be used here
    });
    

    或者使用async/await:

    async function run(x) {
      const a = await import(x);
      // `a` is imported and can be used here
    }
    

    【讨论】:

    • 绝对不会猜到这个!
    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 2012-10-09
    • 2018-11-01
    • 1970-01-01
    • 2019-09-04
    • 2010-12-05
    相关资源
    最近更新 更多