Search code examples
ecmascript-6eslintclass-fields

Eslint - `Parsing error: unexpected token =` error for assigned fat arrow / property initializer


I'm using an arrow function and it's complaining about a parsing error:

Parsing Error: Unexpected token =

However my code is valid (please tell me if i'm mistaken). Additionally, i've set the .eslintrc settings to use es6 parsing:

.eslintrc

{
    "parserOptions": {
        "ecmaVersion": 6,
    }
}

Here's my code:

class foo() {
     // Doesn't like the line below
     // even though it is valid:
     namedFunction = () => {

     }

}

There a way to resolve this error? This makes a huge different in terms of what the value of this from a particular function.


Solution

  • You're using class field (a.k.a. property initializer) syntax, which is not part of ECMAScript 2015 (ES6), nor ES2016 or 2017, and so unsupported by ESLint. It's currently a Stage 3 proposal. If you want to use it with ESLint, you'll need to use babel-eslint. That page describes how to use it, but the gist is:

    Installation

    $ npm install eslint babel-eslint --save-dev
    # or
    $ yarn add eslint babel-eslint -D
    

    Note: babel-eslint requires babel/core@>=7.2.0 and a valid Babel configuration file to run. If you do not have this already set up, please see the Babel Usage Guide.

    Setup

    To use babel-eslint, "babel-eslint" must be specified as the parser in your ESLint configuration file (see here for more detailed information).

    .eslintrc.js

    module.exports = {
      parser: "babel-eslint",
    };
    

    With the parser set, your configuration can be configured as described in the Configuring ESLint documentation.