首页 > 解决方案 > 如何修复'类扩展值未定义不是构造函数或空'NodeJS

问题描述

我按以下顺序有 3 个文件结构,所有这些文件都包含 1 个类

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

我已经查看了这些答案,但我的问题似乎与以下人员描述的任何内容不同。 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
    }
}

事件.js

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

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

    // more code
}

base.js

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

我无法初始化主类,index.js因为这会导致以下错误:

module.exports = class Events extends Base {
                                      ^

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

我是否以某种方式要求以循环方式上课?我不确定我在这里缺少什么。

标签: node.jsclassextends

解决方案


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.


推荐阅读