Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eslint does not recognize private field declaration using nodejs 12

Eslint will not recognize private fields marked with # in class declarations, even though I'm using NodeJS version 12 (which supports them).

I am running NodeJS v12.7.0. I have searched all DuckDuckGo and Google and I cannot find a plugin or option in eslint which will tell it to accept the private field notation (#). I have emca set to version 10.

class MyClass {
   #foo = 'bar';
   #bar = 'foo';

   constructor(foo, bar) {
      this.#foo = foo;
      this.#bar = bar;
   }
   ...
};

When I run eslint on the above code, I get:

2:3 error Parsing error: Unexpected character '#'

The project I'm working on does not use Babel, and I don't want to have to include it just to make private fields work. Any ideas how to make this work without having to resort to using Babel?

(Nothing against Babel of course, it's just on this particular project I don't want it).

like image 451
Doug Barbieri Avatar asked Aug 06 '19 23:08

Doug Barbieri


2 Answers

The upvoted answer is a little out of date, the babel-eslint package has changed, also, you need to make sure you have Babel configured too, in my case I was on a server, so it wasn't.

I blogged about the solution here: https://dev.to/griffadev/setting-up-eslint-to-work-with-new-or-proposed-javascript-features-such-as-private-class-fields-5fm7

TL;DR:

npm i eslint @babel/core @babel/eslint-parser @babel/preset-env -D

Example .eslintrc

{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parser": "@babel/eslint-parser",
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "rules": {
    }
}

Configure .babelrc

{
    "presets": [
      ["@babel/preset-env",
      {
        "shippedProposals": true
      }]
    ]
}

If you are using Jest and you don't have a .babelrc configured already, it will start picking up this new file, this may be a problem. You can workaround this by renaming the .babelrc file to something else, and updating eslint config file:

"babelOptions": {
    "configFile": "./.babel-eslintrc"
 }

like image 153
George Griffiths Avatar answered Oct 27 '22 07:10

George Griffiths


I think that you might have to bite the bullet and use babel-eslint: https://github.com/babel/babel-eslint, which requires that you install babel/core@>=7.2.0

Even though the private class fields are included in node 12, it's still a Stage 3 experimental feature according to the spec (as of August 2019)

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

and add

  "parser": "babel-eslint",

to your .eslintrc.js file

like image 21
Michał Czapliński Avatar answered Oct 27 '22 05:10

Michał Czapliński