Here's my basic setup package.json
{
"scripts": {
"start": "./node_modules/parcel-bundler/bin/cli.js ./public/index.html"
},
"devDependencies": {
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"parcel-bundler": "^1.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
.babelrc
{
"presets": ["env", "react"]
}
Couldn't get any simpler!
This bit of code works totally fine with a create-react-app
import React, { Component } from 'react';
class Counter extends Component {
state = {
counter: 0
};
render() {
const {count} = this.state;
return (
<div>
<button
onClick={() => this.setState({count: count + 1})}
>
Increment counter
</button>
<p>Count: {count}</p>
</div>
);
}
}
export default Counter;
However, when used with the previously mentioned config at the top I get this error:
馃毃 /Users/Alexandre/WebstormProjects/ReactJS/parceljs-react/src/Counter.js:4:10: Unexpected token (4:10)
2 |
3 | class Counter extends Component {
> 4 | state = {
| ^
5 | counter: 0
6 | };
7 |
In order to make it work I had to init the state inside a constructor, like so:
class Counter extends Component {
constructor() {
super();
this.state = { count: 0 }
}
...
}
Any Idea as to what could cause this?
You need babel-plugin-transform-class-properties
as well. (https://babeljs.io/docs/plugins/transform-class-properties/)
This needs to be added to the babelrc file:
plugins": ["transform-class-properties"]
@mischnic Awesome, it works!
What was your reasoning process to figure out babel-plugin-transform-class-properties
was missing?
I remembered from some React documentation that this syntax isn't included in ES6. So I searched for "js class properties" and the third result was the babel plugin.
@speedtreammanga would you be so kind to share your final .babelrc and package.json please ?
@polmoneys sure,
package.json
{
"name": "parceljs-react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "./node_modules/parcel-bundler/bin/cli.js ./public/index.html"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"parcel-bundler": "^1.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
.babelrc
{
"presets": ["env", "react"],
"plugins": ["transform-class-properties"]
}
Having issues ?
sorry been out for the weekend. I'll check asap, looks like I have the right 'config' but maybe I'm missing something. Gracias !
when I include transform-class-properties
I get an error Missing class properties transform
@aluminick See #867
New version of this is called @babel/plugin-proposal-class-properties
:warning:
(As opposed to for example @babel/plugin-transform-class-properties
)
Most helpful comment
You need
babel-plugin-transform-class-properties
as well. (https://babeljs.io/docs/plugins/transform-class-properties/)This needs to be added to the babelrc file: