13

I am using babel to transpile.

I have class BaseComponent which is extended by class Logger.

When I run new Logger() in the browser, I am getting this error

Class constructor BaseComponent cannot be invoked without 'new'

the code that throws this is:

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

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

    return _possibleConstructorReturn(this, Object.getPrototypeOf(Logger).call(this, "n")); //throws here
  }
Nikos
  • 7,295
  • 7
  • 52
  • 88

2 Answers2

14

Due to the way ES6 classes work, you cannot extend a native class with a transpiled class. If your platform supports native classes, my recommendation would be, instead of using the preset es2015, use es2015-node5, assuming you're on Node 5. That will cause Babel to skip compiling of classes so that your code uses native classes, and native classes can extend other native classes.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • oh, that is really limiting, I'm moving to composition anyway! – Nikos Apr 16 '16 at 07:55
  • @loganfsmyth - I am getting similar error. I have a typescript file and it's extending a javascript file (with associated typings file). Is this an issue because typescript can't extend transpiled javascript file and it can only extend another typescript file? – user911 May 01 '17 at 22:28
  • 1
    I just had the same issue as well, trying to extend a TypeScript class in CoffeeScript (which I'm having transpiled by Babel because for some reason Node *still* doesn't support ES6 imports). My solution was to configure `babel-preset-env` to target the latest Node version (see http://babeljs.io/docs/plugins/preset-env/), this transpiles only the `import` statements and leaves the classes alone. – Chris W Oct 29 '17 at 18:04
  • What is the fix for using Node 12? – Jesper1 Nov 13 '19 at 15:59
12

Another solution is to include { exclude: ["transform-es2015-classes"] } in .babelrc

presets: [
   ["env", { exclude: ["transform-es2015-classes"] }]
]

UPDATE: In the latest version of "env" preset plugin names have changed (e.g. it's now "transform-classes"). Use the "debug" option to inspect which plugins are included.

Paulo Alexandre
  • 764
  • 1
  • 9
  • 20