0

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?

1
  • That's not "ES6" code. It's technically not even ES-anything yet. Commented May 8, 2019 at 9:14

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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".

Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.