在 TypeScript 中动态导入模块 [英] Dynamically import module in TypeScript

查看:71
本文介绍了在 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.

推荐答案

ES 提案 动态导入 从 TypeScript 2.4 开始支持.文档位于此处.

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

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

import function is asynchronous and returns a 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
}

这篇关于在 TypeScript 中动态导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆