ES6箭头功能编译错误

时间:2017-02-23 17:28:06

标签: reactjs ecmascript-6

这段代码没有按预期编译,但是应该查看网络上的示例。

ERROR in ./src/main/javascript/app.js
Module build failed: SyntaxError: Unexpected token (66:18)

  64 |     }
  65 | 
> 66 |     addErrorAlert = (title, message) => {
     |                   ^
  67 |         this.state.toastContainer.error(
  68 |             message,
  69 |             title,

有问题的方法,它实际上是扩展React.Component

的EM6类的一部分
addErrorAlert = (title, message) => {
    this.state.toastContainer.error(
        message,
        title,
        {
            timeOut: 10000,
            extendedTimeOut: 10000,
            preventDuplicates: true,
            positionClass: "toast-bottom-full-width",
            showMethod: "fadeIn",
            hideMethod: "fadeOut"
        }
    );
};

WebPack配置

var path = require('path');

var node_dir = __dirname + '/node_modules';

module.exports = {
    entry: './src/main/javascript/app.js',
    devtool: 'sourcemaps',
    cache: true,
    debug: true,
    resolve: {
        alias: {
            'stompjs': node_dir + '/stompjs/lib/stomp.js',
        }
    },
    output: {
        path: __dirname,
        filename: './src/main/resources/static/built/bundle.js'
    },
    module: {
        loaders: [
            {
                test: path.join(__dirname, '.'),
                exclude: /(node_modules)/,
                loader: 'babel-loader',
                query: {
                    cacheDirectory: true,
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

1 个答案:

答案 0 :(得分:0)

您需要启用class properties,这不属于ES6。

presets: ['es2015', 'react'],
plugins: ['transform-class-properties']

或者你可以在构造函数中分配属性。

constructor(props, context) {
  super(props, context);
  this.addErrorAlert = () => { }
}