Why won't Babel transform my class properties?

微笑、不失礼 提交于 2019-12-08 16:37:32

问题


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?


回答1:


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



回答2:


you might be missing "parser":"babel-eslint", in eslintrc.json file. This will ensure babel parser is used.



来源:https://stackoverflow.com/questions/43903632/why-wont-babel-transform-my-class-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!