打字稿:动态导入类 [英] Typescript: dynamically import classes
本文介绍了打字稿:动态导入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢动态导入Typescript类.我使用新的动态函数导入来运行所有程序,但是如何动态类导入?
i like to dynamically import a Typescript Class. I got everything running with the new dynamic function import but how do a dynamic class import?
我有一个肮脏的骇客,看起来像这样:
i have a somehow dirty hack, which looks so:
// main.ts
async function main2() {
const G = './test1'
const TASK_IMPORT_FUNCTION = await import(G)
const TASK_CLASS = TASK_IMPORT_FUNCTION.getTask()
const TASK = new TASK_CLASS(__dirname)
const R_TASK = TASK.run()
}
main2()
// test1.ts
export class Task {
constructor(inputCwd: string) {}
// ...
}
export function getTask() {
return Task
}
所以我的问题是:如何摆脱getTask()函数并以动态方式直接导入类?
So my question is: How can i get rid of the getTask() function and import the class directly in a dynamic way?
// main.ts
async function main2() {
const TASK_IMPORT = await import(G)
const TASK_CLASS = TASK_IMPORT.Task
const TASK = new TASK_CLASS(__dirname)
const R_TASK = TASK.run()
}
main2()
推荐答案
假设 Task
类位于 task.ts
中,则可以使用动态导入:
Assuming Task
class is in task.ts
, you can use dynamic import:
const task = await import("./task");
当您需要导入时.
这篇关于打字稿:动态导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文