React webpack和babel配置问题

时间:2017-05-09 12:42:26

标签: reactjs webpack babel

使用webpack时出现此错误:

ERROR in ./src/pages/clients/components/ClientProfile.js
Module build failed: SyntaxError: Unexpected token (18:17)

  16 |     }
  17 | 
> 18 |     handleSubmit = (person) => {
     |                  ^
  19 |         console.log(person);
  20 |     };
  21 | 

我有.babelrc个配置

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

这是来自devDependencies

package.json
"devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "react-scripts": "0.9.5",
    "webpack": "^2.5.1",
    "webpack-dev-server": "^2.4.5"
  },
  "scripts": {
    "start": "webpack-dev-server --info",
    "build": "webpack",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }

还有webpack.config.js

module: {
        loaders: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.jsx$/,
                loader: 'babel-loader',
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                loader: 'style-loader!css-loader',
                //include: /flexboxgrid/
            }
        ]
    }

我无法弄清楚为什么它的语法失败

handleSubmit = (person) => {
        console.log(person);
    };

有人有想法吗? 感谢。

2 个答案:

答案 0 :(得分:1)

我在您的代码中进行了以下更改,它运行正常。

{
"babel-core": "^6.6.5",
"babel-loader": "^6.2.4",
"babel-plugin-transform-runtime": "^6.6.0",
"babel-preset-es2015-native-modules": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0", //instead of preset-stage-3
}

{
  "presets": [
    "es2015",
    "react",
    "stage-0" //instead of "stage-3"
  ]

}

我会阅读文档并提出原因,直到有人解释它为止。 :)

答案 1 :(得分:0)

The proposal to add class fields to the language目前处于标准化流程的第二阶段。

Babel'舞台'预设的工作原理如下:

  • babel-preset-stage-0仅包含支持Stage 0功能所需的内容。
  • babel-preset-stage-1包含支持Stage 0 1功能所需的内容。
  • 依此类推,直至babel-preset-stage-4

因此,由于您只有babel-preset-stage-3,因此无法使用类字段。要使其正常工作,您应该卸载该软件包,安装babel-preset-stage-2,然后相应地更新配置文件。

有关TC39标准化流程的不同阶段的详细信息,请查看GitHubprocess document