Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Babel transform my class properties?

I have the following person.js

export class Person {
    firstName = ""
    lastName = ""
    middleName = "Nothing"

    constructor(first, last){
       this.firstName = first;
       this.lastName = last;
    }

    get fullName() {
       return this.firstName + " " + this.middleName + " " + this.lastName;
    }
}

Whenever I try to run Webpack, I get a syntax error pointing to the first equal sign between firstName and the double quotes.

If I remove all the properties before the constructor, everything works fine (although I have to include a definition for middleName in the constructor).

I don't know if this is a webpack issue or if this is a Babel issue. If I enter that code into Babel's online Test it out compiler, Babel doesn't seem to have an issue with it.

I have tried configuring Babel using babel-preset-es2015, babel-preset-es2016 and babel-preset-env and nothing changed.

Any idea why that is giving me an error? Are property definitions like that only available in TypeScript?

like image 474
RHarris Avatar asked May 10 '17 22:05

RHarris


People also ask

What is Babel plugin transform class properties?

According to the documentation, this plugin will transform class properties in such a way that you can define class properties using property initializer syntax (ie. by using the = assignment operator). In JavaScript, current class syntax only allows for you to define methods inside of a class, nothing else.

What is Babel plugin transform classes?

Babel is a JavaScript compiler which is used by framework to make code understandable for older browser.

What is Babel plugin proposal class properties?

What is @babel/plugin-proposal-class-properties? This plugin transforms static class properties as well as properties declared with the property initializer syntax.

What is Babel transform?

babel.transform(code: string, options?: Object, callback: Function) Transforms the passed in code . Calling a callback with an object with the generated code, source map, and AST.


1 Answers

You need to use the plugin transform-class-properties or the stage-2 preset which includes this plugin. Without this you won't be able to transform class properties:

npm install --save-dev babel-plugin-transform-class-properties

Or:

npm install --save-dev babel-preset-stage-2

Then make sure to include it in your .babelrc or other means of configuration:

{
  "plugins": [
    "transform-class-properties"
  ]
}

Or:

{
  "presets:" [
    "stage-2"
  ]
}
like image 155
Andrew Li Avatar answered Oct 05 '22 20:10

Andrew Li