Babel错误:如果没有'new',则无法调用类构造函数Foo

Nik*_*kos 9 babel ecmascript-6

我正在使用babel进行转换.

我有class BaseComponent延伸的class Logger.

当我new Logger()在浏览器中运行时,我收到此错误

没有'new'就不能调用类构造函数BaseComponent

抛出这个的代码是:

var Logger = function (_BaseComponent) {
  _inherits(Logger, _BaseComponent);

  function Logger() {
    _classCallCheck(this, Logger);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(Logger).call(this, "n")); //throws here
  }
Run Code Online (Sandbox Code Playgroud)

log*_*yth 10

由于ES6类的工作方式,您无法使用已转换的类扩展本机类.如果您的平台支持本机类,我的建议是,而不是使用预设es2015,使用es2015-node5,假设您在节点5上.这将导致Babel跳过编译类,以便您的代码使用本机类,本机类可以扩展其他本地课程.


pau*_*rio 7

另一个解决方案是排除{ exclude: ["transform-es2015-classes"] }.babelrc

presets: [
   ["env", { exclude: ["transform-es2015-classes"] }]
]
Run Code Online (Sandbox Code Playgroud)

更新:在最新版本的"env"预设插件名称已更改(例如,它现在是"transform-classes").使用"debug"选项检查包含哪些插件.