Unexplained syntax error [duplicate]

2019-07-09 05:58发布

This question already has an answer here:

I am running into a syntax error that I simply cannot explain.

Code:

import React, { Component } from 'react';

class Button extends Component{
  handleClick = () => {
    this.props.onClickFunction(this.props.incrementValue)
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        +{this.props.incrementValue}
      </button>
    );
  }
}

Error Message - Unexpected token (4:14):

  2 |
  3 | class Button extends Component{
> 4 |   handleClick = () => {
    |               ^
  5 |     this.props.onClickFunction(this.props.incrementValue)
  6 |   }
  7 |

I had this code working before, but I wanted to experiment with webpack and since those changes, I am receiving this error. To my understanding, this is a new syntax introduced in es2015. I believe I have everything properly configured:

  "devDependencies": {
    "axios": "^0.17.1",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "bootstrap": "^4.0.0-beta.2",
    "font-awesome": "^4.7.0",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-fontawesome": "^1.6.1",
    "react-scripts": "1.0.17",
    "reactstrap": "^5.0.0-alpha.4",
    "webpack": "~3.9.1",
    "webpack-dev-server": "^2.9.5"
  }

module.exports = {
    entry: "./index.js",
    output:{
        filename:"public/bundle.js"
    },
    module:{
        loaders:[
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query:{
                    presets:['react', 'es2015']
                }
            }
        ]
    }
}

My first thought was, maybe my configuration for es2015 is incorrect. But I tried using the normal function syntax and still received the following error:

  2 |
  3 | class Button extends Component{
> 4 |   handleClick = function(){
    |               ^
  5 |     this.props.onClickFunction(this.props.incrementValue)
  6 |   }
  7 |

2条回答
Anthone
2楼-- · 2019-07-09 06:05

You need to install babel-preset-stage-0 as a dev dependency like this :

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

and preferably as mentioned in the documentation you need to add it to the .babelrc file , (you can create a .babelrc file in the root directory same place where webpack.config.js is ) and add like this :

    {"presets":["react", "es2015", "stage-0"]}

Or if you prefer inside webpack.config.js as you are using , in your query object you can do :

  query: {presets:["react", "es2015", "stage-0"]}
查看更多
疯言疯语
3楼-- · 2019-07-09 06:09

You would need to add the transform-class-properties plugin
And add it to the configuration of babel:

{
  "plugins": [
    "transform-class-properties"
  ]
}
查看更多
登录 后发表回答