0

I am trying to import classes dynamically when they are required.

The following code works;

import TestCommand from "./commands/TestCommand.js"; //At top of the file

And in a function;

let test = new TestCommand();
console.log(test.getName());

And the TestCommand.js;

import Command from "./Command.js";

export default class TestCommand extends Command {
    constructor() {
        super();
        this.name = "Test";
    } 

    getName() {
        return this.name;
    }

    execute() {

    }
}

However, if I attempt to accomplish the same thing within a function, like so;

async function loadCommand(command) {
    let TestCommand = await import("./commands/TestCommand.js");
    let test = new TestCommand();
    console.log(test.getName());
}

I get an error; (node:14264) UnhandledPromiseRejectionWarning: TypeError: TestCommand is not a constructor

Any suggestions on how I could accomplish this?

0 Answers0