1

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()
2
  • What happens if you just write const TASK_CLASS = TASK_IMPORT_FUNCTION.Task? Commented Aug 15, 2018 at 4:29
  • this is running :-) i was blind then. thx a lot! Commented Aug 15, 2018 at 4:42

2 Answers 2

3

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");
  }
}


Sign up to request clarification or add additional context in comments.

1 Comment

A like for the new f.default() string. It will get the class instance using in a JS default way. But a dislike to the chaining notation with async/await. A success on await will step into the next statement if it is OK. Or will throw otherwise.
2

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

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

when you need to import.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.