3

配置

我在我的来编译我的项目。到目前为止,我已经使用了在启用它时应该开箱即用的基本设置:webpack.config.js

// webpack.config.js
// ...

Encore
    // ...
    .enableReactPreset()
;

我试过的:

我继续添加 babel 配置(我认为不需要),希望它能解决问题,但它没有:

.configureBabel(function(babelConfig) {
        // add additional presets
        babelConfig.presets.push('es2017');
    })

代码示例:

这是应该工作的示例,但它不会编译并引发以下错误:

语法错误:意外的令牌

import React, {Component} from 'react';

//This works
const someExteriorHandler = () => {};

export default class Example extends Component {
   //error bad syntax, points specifically at the equal sign.
   someHandler = () => {

   }
   render(){return(<h1>This is a test</h1>)}
}

问题

如何让类中的箭头函数?

4

1 回答 1

0

这个问题就解决了。

在类中分配箭头函数不是 ES6 的一部分。它是即将推出的 ES 版本提案草案的一部分。Babel 能够对其进行转换,但您需要在 babelrc 文件中启用此转换。当您未配置 babel 时,Encore 中提供的默认 babel 配置不会启用实验功能的转译。

安装实验功能

yarn add --dev babel-plugin-transform-class-properties babel-plugin-transform-object-rest-spread

配置 webpack.config.js

.configureBabel(function(babelConfig) {

    //This is needed.

    babelConfig.plugins = ["transform-object-rest-spread","transform-class-properties"]
})

它现在应该可以编译了,所有的 JSX 特性也是如此。

于 2018-05-21T20:46:52.363 回答