divramod
divramod

Reputation: 1504

Typescript: dynamically import classes

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()

Upvotes: 1

Views: 8458

Answers (2)

paliz
paliz

Reputation: 353

do like me

const x = (async () => {
  
  let file = "./v";

  const f = await import( file);
  return f;
})().then(f => {
  
  const s = new f.default();
  s.run();
})
  .catch(error => {
    // Handle/report error
    console.error(error);
  });


here class

export  default class V{
  constructor() {

  }
  run(){
    console.log("fire");
  }
}


Upvotes: 3

jh314
jh314

Reputation: 27802

Assuming Task class is in task.ts, you can use dynamic import:

const task = await import("./task");

when you need to import.

Upvotes: 2

Related Questions