Reputation: 20628
This ReactJS code is valid and produces the desired output:
import React from 'react'
class MyComponent extends React.Component {
state = {'x': 1}
render() {
console.log('render: this.state:', this.state)
return <div>{this.state.x}</div>
}
}
export default MyComponent
But this very similar ES6 code causes error when running with Node.js:
class MyComponent {
state = {'x': 1}
render() {
console.log('render: this.state:', this.state)
return <div>{this.state.x}</div>
}
}
let c = new MyComponent()
c.render()
Here is the error:
$ node foo.js
/Users/lone/foo.js:2
state = {'x': 1}
^
SyntaxError: Unexpected token =
Why does the second example lead to error when the first example runs fine with ReactJS?
Upvotes: 0
Views: 50
Reputation: 6112
As already mentioned, this is not yet standard and create-react-app has a transpilation babel plugin. But you could make it work by using a flag on Node >= 10.9. The flag is --js-flags="--harmony"
.
Upvotes: 0
Reputation: 84912
That syntax is not yet a standard part of javascript (it's currently a stage 3 proposal). It can be used with the help of babel's class-properties plugin to transpile it into standard javascript. Most likely your react project includes this plugin, which is why it works for you in react. Create-react-app, for example, includes the plugin. Without the plugin, react can't use that syntax either.
Upvotes: 3