Search code examples
webpackbabeljs

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?


Solution

  • 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"
      ]
    }