You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript(CommonJS)开发Colyseus聊天室时遇构造函数调用错误

Hey,这个问题我之前开发Colyseus聊天室的时候也踩过一模一样的坑,马上给你梳理解决办法!

解决Colyseus中"Class constructor Room cannot be invoked without 'new'"错误

核心修复方案

问题根源在TypeScript的编译配置上,默认的ES5类继承编译输出和Colyseus的ES6类实现不兼容,调整配置就能搞定:

  1. 更新tsconfig.json编译配置
    确保target至少设为ES2017,同时保留CommonJS模块配置,具体配置如下:

    {
      "compilerOptions": {
        "target": "ES2017",
        "module": "CommonJS",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "moduleResolution": "node",
        "outDir": "./dist",
        "forceConsistentCasingInFileNames": true
      },
      "include": ["src/**/*"]
    }
    
  2. 确保类继承语法规范
    你的ChatRoom类要严格遵循TypeScript标准类继承写法,别用特殊语法:

    import { Room, Client } from "colyseus";
    
    export class ChatRoom extends Room {
      onCreate(options: Record<string, any>) {
        console.log("聊天室初始化完成");
        // 这里编写房间初始化逻辑,比如设置状态、注册消息监听
      }
    
      onJoin(client: Client, options: Record<string, any>) {
        console.log(`用户 ${client.sessionId} 加入聊天室`);
      }
    }
    
  3. 清理旧编译产物重新编译
    先删除之前的dist文件夹,再重新编译,避免残留的旧代码干扰:

    rm -rf dist && tsc
    

错误原因解析

你看到的编译后代码function ChatRoom() { return _super !== null && _super.apply(this, arguments) || this; },是TypeScript把类继承转成ES5语法的产物。但Colyseus的Room类是用ES6类编写的,ES6类的构造函数必须用new关键字调用,而_super.apply这种写法是直接调用构造函数,没有使用new,所以触发了这个错误。

当把target设为ES2017及以上后,TypeScript会直接输出ES6标准的类继承语法(也就是class ChatRoom extends Room),这样就能和Colyseus的Room类完美兼容了。

内容的提问来源于stack exchange,提问作者Alexander Kolarov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:42:24