Babel Syntax error in component definition react

2019-07-05 03:51发布

问题:

I just followed those explantions: https://babeljs.io/blog/2015/06/07/react-on-es6-plus

where it mentions:

// The ES6+ way
class Video extends React.Component {
  static defaultProps = {
    autoPlay: false,
    maxLoops: 10,
  }
  static propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
  }
  state = {
    loopsRemaining: this.props.maxLoops,
  }
}

But if I do:

class AddUserGeolocation extends React.Component {

  static propTypes = {
    alreadyAsked: React.PropTypes.bool.isRequired
  }

  componentDidMount {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        dispatcher(addUser('You', position.coords.latitude, position.coords.longitude))
      });
      dispatcher(askedForUserLocation())
    }
  };

  render() {
    let result = this.props.alreadyAsked ? 'Asked' : 'Not yet'
    return (
      <div>
        {result}
      </div>
    )
  }
}

I get:

ERROR in ./js/containers/AddUserGeolocation.js
Module build failed: SyntaxError: /home/augustin/Workspace/myapp/js/containers/AddUserGeolocation.js: Unexpected token (13:19)
  11 | class AddUserGeolocation extends React.Component {
  12 | 
> 13 |   static propTypes = {
     |                    ^
  14 |     alreadyAsked: React.PropTypes.bool.isRequired
  15 |   }
  16 | 

What is wrong here?

I'm so confused about ES6, ES7, ES2015, Babel etc...

Using:

"

dependencies": {
    "express": "^4.13.4",
    "babel-polyfill": "^6.3.14",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-redux": "^4.1.2",
    "redux": "^3.1.2"
  },
  "devDependencies": {
    "autoprefixer": "^6.3.6",
    "autoprefixer-loader": "^3.2.0",
    "babel-core": "^6.9.1",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-register": "^6.3.13",
    "css-loader": "^0.23.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "node-sass": "^3.7.0",
    "sass-loader": "^3.2.0",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.1",
    "webpack-dev-middleware": "^1.6.1",
    "webpack-hot-middleware": "^2.10.0"
  }

回答1:

For class static properties, you need to install and enable the stage-0 preset in Babel:

$ npm install --save-dev babel-preset-stage-0

And make sure that your Babel configuration uses it:

"presets": [ "es2015", "stage-0" ]