Home > Blockchain >  How to extend class inside module.exports in node js?
How to extend class inside module.exports in node js?

Time:07-29

So, using Node.js v18.3, I don't want to write new class every time in there:

module.exports = {Class1, Class2, /*etc...*/};

That's why I using this way of doing it:

module.exports = {
  ClassName: class ClassName {
    constructor(...args) {
      // properties...
    };
  },
};

But, when I try to extend the class:

module.exports = {
  ClassName: class ClassName {
    constructor(...args) {
      // properties...
    };
  },

  AnotherClass: class AnotherClass extends ClassName {
    // it does not work, sadly...
  },
};

It gives this error:

  AnotherClass: class AnotherClass extends ClassName {
                                           ^

ReferenceError: ClassName is not defined

Tried to work around it with this.ClassName:

  AnotherClass: class AnotherClass extends this.ClassName {
    // does not work too...
  },

But it did not work either:

  AnotherClass: class AnotherClass extends this.ClassName {
                                                ^

TypeError: Class extends value undefined is not a constructor or null

First of all, why does it? Why does it not work in first time, without this.?
Second, how do I fix this or is there any other way doing this, without manually putting all classes in object, as I showed at the beginning of the question?

CodePudding user response:

You’re doing a class expression rather than a class declaration, so at the time your code runs inside module.exports the classes are not defined yet, so cannot be extended from.

Instead of using a single module.exports you could use multiple exports, for example:

exports.Class1 = class Class1 {
  /* … */
};

exports.Class2 = class Class2 extends exports.Class1 {
  /* … */
};
  • Related