1

Is it possible to create a dynamic class without preloading it? I would like to avoid preloading the class, since I'm dynamically importing it. Below is a code example that illustrates what I'm trying to achieve:

  import(namespace).then((DynamicClass) => {
    var classInstance = new DynamicClass();
  }

This currently results in: (node:962) UnhandledPromiseRejectionWarning: TypeError: dynamicClass is not a constructor

When I console.log the DynamicClass, it shows:

{ default: [Function: DynamicClass] }

The class is defined like this:

namespace/index.js

class DynamicClass extends BaseClass {
   //...
}
module.exports = DynamicClass;
4
  • If it's not a constructor, what is it? Should be the first follow up question that debugging starts taking you down. Commented Dec 4, 2020 at 22:40
  • @Taplar Updated the question with more details to illustrate the full use case. Commented Dec 4, 2020 at 22:46
  • So dynamicClass.default might be a constructor Commented Dec 4, 2020 at 22:47
  • @Taplar that did the trick. Can't believe I missed that... Commented Dec 4, 2020 at 22:52

1 Answer 1

3

It looks like your problem has to do with a misunderstanding of modules and the lesser used dynamic import syntax. You are not importing a class you are importing a ES Module. You can use the imported module to access the exported values of the module using the relevant call based on if your desired value is the default export or not.

If your module is exporting a class by default eg

export default class Class(){...}

You would use the default() function available on the module to get the class definition to init.

const module = await import("module-name")
const obj = new module.default();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.