javascript 类型错误:类扩展值未定义不是构造函数或 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48603541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:08:02  来源:igfitidea点击:

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

javascriptnode.js

提问by Owen McGrath

This problem has been causing me to lose my sanity for the last couple of days.

在过去的几天里,这个问题一直让我失去理智。

Here is my directory structure:

这是我的目录结构:

[src]
|- cmds/
|  |- Gh.js
|  \- Help.js
|- commands.js
|...

I am trying to import a class exported by commands.jsinto Help.jsand Gh.js(and any other files I might add in the future). However, I keep getting an error:

我试图通过导入导出的类commands.jsHelp.jsGh.js(以及任何其他文件,我可能会在未来增加)。但是,我不断收到错误消息:

class Gh extends _commands.Command {
                           ^
TypeError: Class extends value undefined is not a constructor or null

All of the files are being transpiled using Babel, with envset to "node": "current"and using the wildcardpackage. I have tried to set it for "browser"to see if it was an issue of it being too "advanced", but I got a different error about super functions (or something), which I assume is the same issue.

所有文件都使用 Babel 进行转译,env设置为"node": "current"并使用wildcard包。我试图设置它"browser"以查看是否是它过于“高级”的问题,但是我遇到了关于超级函数(或其他东西)的不同错误,我认为这是同一个问题。

Here is the class being exported from commands.js:

这是从commands.js以下导出的类:

export class Command {
  constructor (msg) {
    this.id = msg.author.id
    this.msg = msg
  }
  action () {}
  get data () {
    return readData().user[this.id]
  }
  updateUserData (key, val) {
    updateUserData(this.id, key, val)
  }
  sendMsg (data) {
    sendMsg(this.msg, data)
  } 
}

...and here is cmds/Gh.js, one of the files that I am trying to import Commandinto:

...这是cmds/Gh.js我试图导入的文件之一Command

import {Command} from '../commands'

export class Gh extends Command {
  constructor (msg) {
    super(msg)
    this.desc = 'Returns GitHub repository link and exits'
  }
  action () {
    this.sendMsg('GitHub link: https://github.com/owm111/knife-wife')
  }
}

I tried putting Commandinto both of the cmds/, and they worked perfectly. However, when moving it back into commands.js, it broke again. I tried changing the path it is importing from from ../commandsto ./../commands, ../commands.js, ./../commands.js; none worked. I moving commands.jsinto cmds/, still broke. I tried to console.log(Command)in both of the cmds/, but they both returned undefined.

我尝试将Command两者都放入cmds/,并且它们工作得很好。然而,当把它移回 时commands.js,它又坏了。我尝试将其导入的路径从 from../commands更改为./../commands, ../commands.js, ./../commands.js; 没有工作。我搬进commands.js去了cmds/,还是破了。我试图console.log(Command)在两者中cmds/,但它们都返回了undefined

All of this makes it look like is a problem with importing, but I cannot figure out what for the life of me. Please help.

所有这些使它看起来像是导入的问题,但我无法弄清楚我的生活是什么。请帮忙。

回答by MBer

If anyone else sees this error, the first thing to look for is circular dependencies. Import file A into B, B into some other file C, and so on. If any of C through Z is imported into A, then JS will not be able to ensure that a file is defined at the time that another file needs it (and will not try to go back and fill in the blanks later).

如果其他人看到此错误,首先要查找的是循环依赖项。将文件 A 导入 B,将 B 导入其他文件 C,依此类推。如果将 C 到 Z 中的任何一个导入到 A 中,那么 JS 将无法确保在另一个文件需要它时定义了一个文件(并且以后不会尝试返回并填充空白)。

This was likely the case here, since there was clearly other code not posted, and it only appeared when file dependencies were introduced. The problem exists regardless of file structure: the only structure guaranteed to avoid it is a single giant JS file. The solution is to ensure a strict tree structure of relationships between classes, and use factory methods or alternative communications like emitters to keep the couplings loose.

这很可能是这里的情况,因为显然没有发布其他代码,并且只有在引入文件依赖项时才会出现。无论文件结构如何,问题都存在:唯一保证避免它的结构是单个巨大的 JS 文件。解决方案是确保类之间关系的严格树结构,并使用工厂方法或替代通信(如发射器)来保持耦合松散。

If you have more than a couple import / require statements, I recommend periodically running a checker like Madgeto find and optionally visualize any loops before they become hard to undo.

如果您有多个 import / require 语句,我建议定期运行像Madge这样的检查器来查找并可选地可视化任何循环,以免它们变得难以撤消。

npm install --save-dev madge
node_modules/madge/bin/cli.js --warning --circular --extensions js ./

回答by Darien Creamer

This is just a simple fix for node.js. Remove export from your class and at the bottom of your file put this in it.

这只是 node.js 的一个简单修复。从您的班级中删除导出,并在您的文件底部将其放入其中。

module.exports.Command;

Now if you want to use the command class anywhere you just need to put this in each file where you would like to use it.

现在,如果您想在任何地方使用命令类,只需将它放在每个文件中您想使用它的地方。

var { Command } = require('Command.js');

回答by aygunyilmaz

I got this error that "Sequelize TypeError: Class extends value undefined is not a constructor or null, NodeJS"and solved it using that. If you have the same error, you can use the following solution that I've tried to explain it in code.

我收到了“Sequelize TypeError: Class extends value undefined is not a constructor or null, NodeJS”的错误,并使用它解决了它。如果你有同样的错误,你可以使用我试图在代码中解释它的以下解决方案。

for example:

例如:

module.exports = (sequelize, DataTypes) => {

    // Modeling a table: Inheritance
    class Todo extends sequelize.Model {} // (!) Error

    // if you want to use the above line, add the following line to "lib\sequelize.js file
    // Sequelize.prototype.Model = Model; // add this line here

    class Example extends sequelize.Sequelize.Model { }

    Example.init({
        title: DataTypes.STRING,
        description: DataTypes.STRING,
        status: DataTypes.BOOLEAN
    }, {
        sequelize,
        modelName: 'todo',
        timestamps: true
    });

    return Example;
};

回答by keithphw

For people getting this error when using JSweetjava to javascript transpiler, I was able to fix it by enabling the 'bundle' option, mentioned here:

对于在使用JSweetjava 到 javascript 转译器时遇到此错误的人,我能够通过启用此处提到的“捆绑”选项来修复它:

Bundle up all the generated code in a single file, which can be used in the browser. The bundle files are called 'bundle.ts', 'bundle.d.ts', or 'bundle.js' depending on the kind of generated code. NOTE: bundles are not compatible with any module kind other than 'none'.

将所有生成的代码打包在一个文件中,可以在浏览器中使用。根据生成的代码类型,捆绑文件被称为“bundle.ts”、“bundle.d.ts”或“bundle.js”。注意:捆绑包与“无”以外的任何模块类型都不兼容。

This is part of my POM which contains the 'bundle true' addition:

这是我的 POM 的一部分,其中包含“bundle true”添加:

<plugin>
                <groupId>org.jsweet</groupId>
                <artifactId>jsweet-maven-plugin</artifactId>
                <version>${jsweet.transpiler.version}</version>
                <configuration>
                    <verbose>true</verbose>
                    <tsOut>target/ts</tsOut>
                    <outDir>target/js</outDir>
                    <candiesJsOut>webapp</candiesJsOut>
                    <targetVersion>ES6</targetVersion>
                    <module>none</module>
                    <moduleResolution>classic</moduleResolution>
                    <bundle>true</bundle>
                </configuration>
                <executions>
                    <execution>
                        <id>generate-js</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>jsweet</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Then re-run 'mvn generate-sources', and make sure that you change the index.html file to load the new bundle.js file:

然后重新运行 'mvn generate-sources',并确保更改 index.html 文件以加载新的 bundle.js 文件:

<html>
<head>
<link rel="icon" type="image/png" href="logo.png">
<link rel="shortcut icon" href="logo.png">
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</head>

<body>
    <p>Test page</p>
    <p id="target"></p>
    <script type="text/javascript" src="../webapp/j4ts-0.7.0-SNAPSHOT/bundle.js"></script>
    <script type="text/javascript" src="../target/js/bundle.js"></script>
</body>
</html>

回答by HereHere

In my case: I was importing a non-existing class:

就我而言:我正在导入一个不存在的类:

Counter.js:

计数器.js:

import React, { Compontent } from 'react';

class Counter extends Compontent {

App.js:

应用程序.js:

import React from 'react';
import Counter from './components/Counter';

function App() {