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
}
So my question is: How can i get rid of the getTask() function and import the class directly in a dynamic way?
Solution
// 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()
const TASK_CLASS = TASK_IMPORT_FUNCTION.Task?