简体   繁体   中英

Arrow functions in class throw error with webpack-encore

Configuration

I'm using with my project to compile my project. Up till now, I've used the basic webpack.config.js setup that should work out of the box with react when enabling it :

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

Encore
    // ...
    .enableReactPreset()
;

What I've tried:

I went ahead and added babel configurations (that I don't think are needed) in hope that it would solve the problem, but it didn't:

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

Code example:

Here is an example of what should work, but it doesn't compile and throws the following error:

Syntax Error: Unexpected token

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

Question

How do I get the babel compiler in to compile Arrow functions in classes?

This problem was solved .

Having assignment of arrow functions in a class is not part of ES6. It is part of a draft proposal for an upcoming ES version. Babel is able to transpile it, but you will need to enable this transformation in the babelrc file. The default babel config shipped in Encore when you don't configure babel does not enable the transpilation of experimental features.

Install experimental features

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

Configure webpack.config.js

.configureBabel(function(babelConfig) {

    //This is needed.

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

It should compile now, with all JSX features as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM