【问题标题】:Unexplained syntax error [duplicate]无法解释的语法错误[重复]
【发布时间】:2018-05-16 17:25:29
【问题描述】:

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

代码:

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 |

【问题讨论】:

    标签: reactjs webpack ecmascript-6 babeljs


    【解决方案1】:

    您需要像这样安装babel-preset-stage-0 作为开发依赖项:

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

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

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

    或者,如果您更喜欢使用 webpack.config.js,在您的查询对象中,您可以这样做:

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

    【讨论】:

    • 我认为这可能已经成功了!在编译之前,我需要解决一些其他问题。我会尽快通知你的。
    • 没问题,有什么问题请告诉我:)
    • 做到了!谢谢!
    • 很高兴为您提供帮助:)
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回复。我进行了您建议的更改,但现在我得到了“缺少类属性转换”。同一行出错。
    • 你是否使用 webapck 并在你的 webpack 加载器中为 babel 进行了其他配置?
    • 我唯一的配置是我在问题中发布的配置。
    • 如果你使用的是.babelrc 文件,那么你的webpack 加载器中不需要query 部分。如果您没有 .babelrc 文件,则将 'stage-0' 预设添加到 babel 查询属性中的数组末尾(在 webpack 中)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    相关资源
    最近更新 更多