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?
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.
Babel is a JavaScript compiler which is used by framework to make code understandable for older browser.
What is @babel/plugin-proposal-class-properties? This plugin transforms static class properties as well as properties declared with the property initializer syntax.
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.
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"
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With