Javascript ES6 TypeError: Class constructor Client cannot be invoked without 'new'

后端 未结 6 716
深忆病人
深忆病人 2020-11-30 02:59

I have a class written in Javascript ES6. When I try to execute nodemon command I always see this error TypeError: Class constructor Client cannot be invo

6条回答
  •  天涯浪人
    2020-11-30 03:41

    The problem is that the class extends native ES6 class and is transpiled to ES5 with Babel. Transpiled classes cannot extend native classes, at least without additional measures.

    class TranspiledFoo extends NativeBar {
      constructor() {
        super();
      }
    }
    

    results in something like

    function TranspiledFoo() {
      var _this = NativeBar.call(this) || this;
      return _this;
    }
    // prototypically inherit from NativeBar 
    

    Since ES6 classes should be only called with new, NativeBar.call results in error.

    ES6 classes are supported in any recent Node version, they shouldn't be transpiled. es2015 should be excluded from Babel configuration, it's preferable to use env preset set to node target.

    The same problem applies to TypeScript. The compiler should be properly configured to not transpile classes in order for them to inherit from native or Babel classes.

提交回复
热议问题