原因不明的语法错误

时间:2017-12-02 22:13:55

标签: reactjs webpack ecmascript-6 babeljs

我遇到了一个语法错误,我无法解释。

代码:

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>
    );
  }
}

错误消息 - 意外的令牌(4:14):

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

之前我有这个代码工作,但我想尝试使用webpack,因为这些更改,我收到此错误。据我了解,这是es2015中引入的新语法。我相信我已经正确配置了所有内容:

  "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']
                }
            }
        ]
    }
}

我的第一个想法是,也许我对es2015的配置不正确。但我尝试使用普通函数语法,但仍然收到以下错误:

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

2 个答案:

答案 0 :(得分:2)

您需要安装babel-preset-stage-0作为dev依赖项,如下所示:

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

并且最好如documentation中所述,您需要将其添加到.babelrc文件中,(您可以在.babelrc的同一位置的根目录中创建webpack.config.js文件}是)并添加如下:

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

或者如果您喜欢在webpack.config.js内使用,可以在查询对象中执行以下操作:

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

答案 1 :(得分:0)

您需要添加transform-class-properties plugin
并将其添加到babel的配置中:

{
  "plugins": [
    "transform-class-properties"
  ]
}