没有'new' - 使用commonjs的typescript时,不能调用类构造函数

问题描述 投票:2回答:2

我正在与colyseus(节点游戏服务器框架)进行服务器端聊天。我使用typescript与module:commonjs因为colyseus是建立在commonjs之上的。

我有课程ChatRoom扩展Colyseus.Room。在运行时我收到此错误:

Class constructor Room cannot be invoked without 'new'.

而javascript中的麻烦:

function ChatRoom() {
   return _super !== null && _super.apply(this, arguments) || this;
}

来自typescript类:

import {Room} from "colyseus";

export class ChatRoom extends Room {

    onInit(options) {
        console.log("BasicRoom created!", options);
    }

    onJoin(client) {
        this.broadcast(`${ client.sessionId } joined.`);
    }

    onLeave(client) {
        this.broadcast(`${ client.sessionId } left.`);
    }

    onMessage(client, data) {
        console.log("BasicRoom received message from", client.sessionId, ":", data);
        this.broadcast(`(${ client.sessionId }) ${ data.message }`);
    }

    onDispose() {
        console.log("Dispose BasicRoom");
    }
  }

编译后删除故障行时,很容易跳过该错误。但是没有创建基类,这不是一个完整的解决方案。

我搜索了这个问题,它似乎与babel transpiler有关,虽然我不使用babel。我只使用tsc / tsconfig.json。

node.js typescript commonjs
2个回答
13
投票

TypeScript将类转换为其ES5对应物,但这样就必须将整个类层次结构转换为ES5。如果父类是未传输的(本机类或导入的ES6类,包括使用Babel转换的类),这将不起作用,因为TypeScript依赖于var instance = Parent.call(this, ...) || this技巧来调用父构造函数,而ES6类应仅使用new调用。

通过将TypeScript target option设置为es6,可以在Node.js中解决此问题。现代Node.js版本支持ES6类,不需要对它们进行转换。


0
投票

我使用javascript,webpack和babel(但没有TypeScript)遇到了同样的问题。

我找到了一个基于ES6/Babel Class constructor cannot be invoked without 'new'的解决方案

我需要在我的babel装载机中明确包括colyseus。以下是我的webpack配置文件中的代码段:

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: /colyseus/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
© www.soinside.com 2019 - 2024. All rights reserved.