37

Thanks for reading my post I get this error on my code : "Class extends value # is not a constructor or null" Here is my code, I'm trying to export/import classes.

monster.js :

const miniMonster = require("./minimonster.js");

class monster {
  constructor(options = { name }, health) {
    this.options = options;
    this.health = 100;
    this.heal = () => {
      return (this.health += 10);
    };
  }
}

let bigMonster = new monster("Godzilla");
console.log(bigMonster);

console.log(bigMonster.heal());

let mini = new miniMonster("Demon");
console.log(mini);
console.log(mini.heal());

module.exports = monster;

minimonster.js :

const monster = require("./monster.js");

class miniMonster extends monster {
  constructor(options) {
    super(options);
    this.health = 50;
    this.heal = () => {
      return (this.health += 5);
    };
  }
}

let miniM = new miniMonster("Jon");
console.log(miniM);

module.exports = miniMonster;

Thank you for any help given,

Have a good day

Charlote22
  • 1,035
  • 3
  • 11
  • 13

6 Answers6

23

I see at least one issue with your requires.

  • monster.js first line is const miniMonster = require("./minimonster.js");
  • minimonster.js first line is const monster = require("./monster.js");

This is a problem, you can not have both files evaluate at the same time. I would not require minimonster from monster.js

This may fix your issue.

kigiri
  • 2,952
  • 21
  • 23
18

When I get this error message it is because I have done my module.exports wrong. eg.

publicclass.js

class PublicClass {
.....
}

module.exports.PublicClass = PublicClass;

instead of

module.exports = PublicClass;
Dave Pile
  • 5,559
  • 3
  • 34
  • 49
6

For me, I had introduced a circular dependency.

lwdthe1
  • 1,001
  • 1
  • 16
  • 16
1

Correct Code:

//Export from monster.js (but don't import minimonster.js)
class monster {
.....
}
let bigMonster = new monster("Godzilla");
module.exports = monster;

//Import in minimonster.js
const monster = require("./monster.js");
class miniMonster extends monster {
.....
}
let miniM = new miniMonster("Jon");
module.exports = miniMonster;

A circular dependency happens when module A depends on something in module B and module B depends on something in module A. This means to compile module A you must first compile module B, but you can't do that as B requires A to be already compiled.

So to avoid circular dependency we should not import a module (minimonster.js) that is exporting a module (monster.js) in that same module (monster.js).

Bikash Nath
  • 23
  • 1
  • 7
0

In my case, I put extended class inside of {}.

const { ParentClass } = require("./ParentClass");

class ChildClass extends ParentClass {    
}

module.exports = { ChildClass };

And:

class ParentClass {
    constructor() {}
}

module.exports = { ParentClass };
ParisaN
  • 1,816
  • 2
  • 23
  • 55
-7

I used as per below line.

import Base from "./base

and its working fine now

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53