Babel error: Class constructor Foo cannot be invoked without 'new'
Asked Answered
R

2

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
  }
Roughshod answered 12/4, 2016 at 15:26 Comment(3)
Is this the output of babel, or code that you've written? (If this is output, show the code you wrote.)Vulpecula
What is BaseComponent?Feriga
@Feriga is just a ES6 classRoughshod
F
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.

Feriga answered 15/4, 2016 at 21:43 Comment(4)
oh, that is really limiting, I'm moving to composition anyway!Roughshod
@Feriga - 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?Heterotrophic
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 babeljs.io/docs/plugins/preset-env), this transpiles only the import statements and leaves the classes alone.Workbook
What is the fix for using Node 12?Huldahuldah
R
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.

Rowdyish answered 17/11, 2017 at 17:22 Comment(4)
You mean to include transformation of classes into functions?Humfried
Perfect solution.Ingraft
This is the solution but it should be include instead of exclude.Divergent
Thanks it works! include: ['transform-classes'],Jadda

© 2022 - 2024 — McMap. All rights reserved.