Search code examples
node.jsclassextends

How to fix 'Class extends value undefined is not a constructor or null' NodeJS


I have 3 files structure in the following order all of which contain 1 class

main.js extends events
events.js extends base
base.js

I've looked into these answers but my problem doesn't appear to look like anything of the following people described. TypeError: Class extends value undefined is not a function or null

main.js

const { Events } = require('./events.js');

module.exports = class Main extends Events {
    constructor(token) {
        super();

        // Some code
    }
}

events.js

const { Base } = require('./base.js');

module.exports = class Events extends Base {
    constructor() {
        super();
    }

    // more code
}

base.js

module.exports = class Base{
    constructor() {
        // Code
    }
}

I'm unable initialize the main class in index.js as this results in the following error:

module.exports = class Events extends Base {
                                      ^

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

Am I somehow requiring the classes in a circular way? I'm not sure what I'm missing here.


Solution

  • It is possible you are creating some sort of circular dependency loop by the way you import external modules in index.js.

    But, it appears that mostly you just need to change from this:

    const { Base } = require('./base.js');
    

    to this:

    const Base = require('./base.js');
    

    And from this:

    const { Events } = require('./events.js');
    

    to this:

    const Events = require('./events.js');
    

    When you do something like this:

    const { Base } = require('./base.js');
    

    it's looking for a property on the imported module named Base, but there is no such property. You exported the class as the whole module. So, that's what you need to assign to your variable Base (the whole module):

    const Base = require('./base.js');
    

    And the code in index.js that imports main.js will have to be done properly too if it isn't already being done right.