Eslint does not recognize private field declaration using nodejs 12 - node.js

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

2021 Update: You do not need babel for this anymore!
You can simply update eslint to v8.0.0 and above.
See eslint release notes: https://eslint.org/blog/2021/10/eslint-v8.0.0-released#highlights
Make sure this is in your .eslintrc file or similar:
{
"parserOptions": {
"ecmaVersion": 13
}
}
You can also just use latest instead of specifically version 13.

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

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

In regards to Visual Studio 2019, I found that the #babel/eslint-parser doesn't work with it but the older babel-eslint does. Other set up per #George's answer.
Visual Studio 2019 version as at time of answer: 16.9.5

Unless you really, really want that specific file linted I would avoid adding new dependencies just to make tests pass. My advice in this case would be to add
ignorePatterns: ["path/to/file(s).js"],
in your .eslintrc.js file. That will avoid linting that specific file. If you really want to lint it, do a substitution of # by __, lint, and change it back. I know, it's a hack, but it does not introduce any kind of dependency and it works.

Related

How do you reenable esLint squiggly lines after adding Prettier?

Description
I am trying to configure esLint to work with Prettier in VSCode. I am able to successfully install esLint, but when I add Prettier and add it to extends in the esLint config, the squiggly lines provided by esLint disappear. I have provided more details below.
Setup Steps
1. Install esLint and VSCode extension
I installed the esLint VSCode extension, and followed the esLint getting started docs to enable esLint. It works exactly as expected. In this example test code,
console.log("This is a test")
it identifies three issues which is the desired result:
2. Install Prettier and VSCode extension
Next, I installed Prettier and the VSCode extension without any difficulty. In this part of the Prettier Docs, it says I will need to install eslint-config-prettier.
3. Install eslint-config-prettier
This is where the issue occurs. The installation goes fine, but in the eslint-config-prettier github page it says:
Then, add "prettier" to the "extends" array in your .eslintrc.* file. Make sure to put it last, so it gets the chance to override other configs.
{
"extends": [
"some-other-config-you-use",
"prettier"
]
}
The moment I add this to my .eslintrc.json and save the config, the squiggly lines disappear:
I am not sure how to resolve this. I went through the docs for esLint, Prettier, and eslint-config-prettier but none of the optional settings listed in the docs are bringing back the squiggles.
Configurations
.eslintrc.json
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"airbnb-base",
"prettier"
],
"overrides": [],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {}
}
.prettierrc.json
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}
esLint Output
[Info - 1:48:20 PM] ESLint server is starting
[Info - 1:48:20 PM] ESLint server running in node v16.14.2
[Info - 1:48:20 PM] ESLint server is running.
[Info - 1:48:21 PM] ESLint library loaded from: /Users/georgeciesinski/Documents/Repositories/todo-list/node_modules/eslint/lib/api.js
Additional Info
My desired behaviour is for esLint to provide the squiggly lines so I can fix the issues manually. At the end, I will run Prettier from the CLI.
I am also using the airbnb eslint config.
I am using an M1 macbook running MacOS Ventura in case this matters.
I was able to find an answer to my query. In short, the configuration works despite my console.log test appearing to fail. The eslint-config-prettier configuration turns off some esLint rules as expected. Per the github docs:
Extending "prettier" turns off a bunch of core ESLint rules, as well as a few rules from these plugins:
#typescript-eslint/eslint-plugin
#babel/eslint-plugin
eslint-plugin-babel
eslint-plugin-flowtype
eslint-plugin-react
eslint-plugin-standard
eslint-plugin-unicorn
eslint-plugin-vue
I was aware of this, but I did not realize that the single quotes and semicolon rules were included in this, both of which stopped working when I extended Prettier. Further testing proved that esLint is in fact linting code that doesn't adhere to the remaining airbnb-base rules which have not been disabled by eslint-config-prettier.

ESLint Vue plugin showing false positives for vue/comment-directive

After migrating from VueCLI to Vite, I have to do the linting "manually" as far as I understand; correct me if I'm wrong.
As I only want to lint my .ts and .html files (I separate them even for components), I have this script in my package json:
"lint": "eslint --ext .ts --ext .html src/"
It found some issues like missing :key in loops, but it also shows me this error for each template:
error clear vue/comment-directive
And this is always the closing tag of any root elements within my template.html
If there is only one root element I get one warning for the file, if there are multiple root elements I get a warning for each closing tag.
I don't understand what this rule complains as, according its documentation, it is there for the eslint-disable comments, which I don't have in my templates.
I had the same issue but in nuxt with eslint, i just needed to update eslint-config and eslint-module:
"#nuxtjs/eslint-config": "^5.0.0",
"#nuxtjs/eslint-module": "^3.0.1",
source: https://github.com/nuxt/eslint-plugin-nuxt/issues/121
I've just updated my npm dependencies and I have the same error.
I was reading the eslint documentation and finally I've realized that you can remove the false error if you setup the rule in the .eslintrc.js config file.
this is my .eslintrc.js config file:
module.exports = {
root: true,
env: {
browser: true,
node: true
},
parserOptions: {
parser: 'babel-eslint'
},
extends: [
'#nuxtjs',
'prettier',
'prettier/vue',
'plugin:prettier/recommended',
'plugin:nuxt/recommended'
],
plugins: [
'prettier'
],
// add your custom rules here
rules: {
"vue/comment-directive": 0
}
}
add the rule "vue/comment-directive": 0 and that is!, the error message is removed!.
the possible values are:
0 means disabled
1 means warning
2 means error
Try to change it in your IDE to how it works
(In my case I've had to stop the server and re-run it every time that I've changed a value in this config file.)
I have the same error.
I was taught how to fix this error.
https://qiita.com/tashinoso/items/a72741ca8e2fd928ca77#comment-3e6cd674353056ecbb3a
module.exports = {
...
overrides: [
{
files: ["*.vue"],
processor: "vue/.vue"
}
]
}
Set this snippet on .eslintrc.js
"vue/comment-directive": ["error", {
"reportUnusedDisableDirectives": false
}]
Solve my issue, i wonder why. Solution from documentation
Node v12.20.0
This is a kind of a temporary fix that worked for me and I think it will work for you as well.
vue/comment-directive
This rule is included in all of "plugin:vue/base", "plugin:vue/essential", "plugin:vue/vue3-essential", "plugin:vue/strongly-recommended", "plugin:vue/vue3-strongly-recommended", "plugin:vue/recommended" and "plugin:vue/vue3-recommended".
ESLint doesn't provide any API to enhance eslint-disable functionality and ESLint rules cannot affect other rules. But ESLint provides processors API.
This rule sends all eslint-disable-like comments as errors to the post-process of the .vue file processor, then the post-process removes all vue/comment-directive errors and the reported errors in disabled areas.
All you need to do is add
eslint-disable-next-line vue/component-tags-order
this line as comment above anywhere you using comments within tags in each block you need to specify if comments are added.
For more information please visit:- https://eslint.vuejs.org/rules/comment-directive.html

Yarn workspaces -- package alias

TL;DR How can I create an alias for a local yarn workspace dependency?
I've tried yarn workspaces before and never succeeded, and I'm giving it another try.
I've set "workspaces": ["packages/*"] in package.json.
For each package, I decided to use the naming convention #-/package-name to prevent naming conflicts and without worrying about having namespaces for internal packages.
When adding packages as dependencies, I've been following a style where I use an interface name for resolution, but point that towards a concrete implementation. This is what I did before using yarn workspaces:
"dependencies": {
"my-interface-name": "file:some/path/to/packages/some-concrete-implementation"
}
This is basically to allow what I like to call compile-time static dependency injection. And it also means each package can individually name their interface dependencies appropriately to their need and to prevent naming conflicts.
However, I can't figure out how to accomplish this with yarn workspaces. How do I create an alias for my yarn workspaces package #-/some-concrete-implementation called my-interface-name?
What I've already tried with no success:
Defining the dependency like "my-interface-name": "#-/some-concrete-implementation"} - for some reason this causes yarn to look for #-/some-concrete-implementation on the npm registry instead of in the local workspace
I've also tried to use the workspace protocol: "my-interface-name": "workspace:#-/some-concrete-implementation"} but it still looks for the package on the npm registry!
What I haven't yet tried and could work but removes benefits of using yarn workspaces in the first place:
"dependencies": {"my-interface-name": "file:../../node_modules/#-/some-concrete-implementation"}"
Have you seen the resolutions package.json key? Is it what you need?
I've used it for aliasing/overriding external packages but the example in the docs shows it working with local packages.
Resolutions
Allows you to override a version of a particular nested dependency. See the Selective Versions Resolutions RFC for the full spec.
{
"resolutions": {
"transitive-package-1": "0.0.29",
"transitive-package-2": "file:./local-forks/transitive-package-2",
"dependencies-package-1/transitive-package-3": "^2.1.1"
}
}
From the RFC:
"**/a" denotes all the nested dependencies a of the project.
"a" is an alias for **/a (for retro-compatibility, see below, and because if it wasn't such an alias, it wouldn't mean anything as it would represent one of the non-nested project dependencies, which can't be overridden as explained below).
So, I believe the rule you need is:
"**/my-interface-name": "file:some/path/to/packages/some-concrete-implementation"
// OR equivalent
"my-interface-name": "file:some/path/to/packages/some-concrete-implementation"
I believe it works in the package's package.json. Worst case you can hoist it to the workspace root and make the rule specific to the workspace e.g. "a/b".
The workspace: alias protocol (available in pnpm too) seems the direction to take.
I've also tried to use the workspace protocol: "my-interface-name": "workspace:#-/some-concrete-implementation"} but it still looks for the package on the npm registry!
Be sure to have yarn 3 installed, otherwise you'll run into weird issues.
Note that the syntax of "my-interface-name": "workspace:#-/some-concrete-implementation" looks incorrect.
It should be "#xxx/some-concrete-implementation": "workspace:*", assuming the name of linked the package is "name": "#xxx/some-concrete-implementation".
With this in mind you don't even need to create a specific #-/name. With workspace protocol, yarn will ensure it's never downloaded from npm. It becomes an internal workspace dependency.
PS:
Yarn 3 installation
Generally a simple yarn set version 3.0.2 && yarn plugin import workspace-tools) will work.
To avoid pnp current limitation, check the generated config .yarnrc.yml and ensure nmLinker is set to 'node-modules'
# Yarn 2+ supports pnp or regular node_modules installs. Use node-modules one.
nodeLinker: node-modules
plugins:
- path: .yarn/plugins/#yarnpkg/plugin-workspace-tools.cjs
spec: "#yarnpkg/plugin-workspace-tools"
yarnPath: .yarn/releases/yarn-3.0.2.cjs
PS: you might want to add this to .gitignore too
.yarn/*
!.yarn/patches
!.yarn/releases
!.yarn/plugins
!.yarn/sdks
!.yarn/versions
.pnp.*
Run a yarn install just after.
About package.json's
Like you did, the root package.json will define the workspace paths:
{
"name": "monorepo",
"workspaces": [
"packages/*" // Enable package discovery in packages/* directory.
],
// ...
"devDependencies": {
"husky": "7.0.2", // Only what's needed for monorepo management
}
In your app packages/app/package.json
{
"name": "my-app",
"devDependencies": {
"#types/node": "16.10.1",
//...
},
"dependencies": {
// Assuming the name of packages/shared is "#your-org/some-concrete-implementation",
// we explicitly declare the dependency on it through
// workspace: alias (package-manager perspective)
"#your-org/some-concrete-implementation": "workspace:*",
}
}
You consumed package should declare the same name
{
"name": "#your-org/some-concrete-implementation",
}
Bonus: Typescript aliases
If your project is written in ts, you can even replicate your paths through
typescript path mapping. It will allow to include the files just as is (no prior compilation needed).
Following your example, just edit a ./packages/xxx/tsconfig.json in this way
{
"compilerOptions": {
// here baseUrl is set at ./src (good practice), can
// be set to '.'
"baseUrl": "./src",
"paths": {
// Declare deps here (keep them in sync with what
// you defined in the package.json)
// PS: path are relative to baseUrl
"#your-org/some-concrete-implementation/*": ["../../some-concrete-implementation/src/*"],
// if you have a barrel in ui-lib
"#your-org/some-concrete-implementation": ["../../some-concrete-implementation/src/index"],
}
},
}
PS: for non typescript: babel/plugin-module-resolver can be used in a similar manner.

Why does ESLint throw an error while using export/import statement on Node.js 12.13.0?

I have a project built on Node.js, DynamoDB and other AWS services, deployed on Serverless architecture. I also have the ESLint package installed.
I am getting the following error:
ESLint: Import and export declarations are not supported yet on Node 8.0.0. (node/no-unsupported-features)
Following are the details of my project:
Node version: 12.13.0
NPM version: 6.12.0
Serverless version: 1.40.0
ESLint: 6.8.0
I have double verified by node version of my project and my local. Both are the same (12.13.0).
I am able to use async/await but whenever I try using import/export, it gives me the error.
Following is my .eslintrc file :
{
"extends" : [
"eslint:recommended",
"plugin:node/recommended"
],
"plugins": [
"promise",
"node"
],
"env" : {
"browser" : false,
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"impliedStrict": false
},
"globals" : {
},
"rules": {
"no-console": 0,
"no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": false }],
"node/no-unpublished-require": [
"error",
{
"allowModules": [
"aws-sdk"
]
}
],
"node/no-unsupported-features": ["error", {
"version": 8,
"ignores": []
}]
}
}
`
Node.js by default uses Common.js style for import/export.
In the new versions of Node.js you can use different extensions or the --experimental-modules option in the command line.
*.mjs you use ES6 import/export
*.js or *.cjs you use commonjs
If you consider that ECMAScript modules import/export are still experimental, I would say that ESLint is quite correct.
You might want to override EsLint rules in order to make it work with that.
Firstly consider that the rule you mentioned is obsolete so you might want to use the new ones => https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-unsupported-features.md
Because those rules are obsolete I would suggest you to take a look at your eslint and its external rulesets version (if you use them) and try again.
In any case...
Check/create the .eslintrc.json file in the root of your project and override the project rules you might want to change.
Just stumpled upon a similiar error.
In my case i solved it by adding the engines definition to package.json
"engines": {
"node": ">=12.13.0"
}
I am not sure if this solves you problem but a quite similar issue can be found here.

Is there a way to ignore test files for eslint-plugin-security?

With a node.js project, I've added eslint-plugin-security and it is giving a lot of warnings for code in my test/spec files (using mochajs). Since the test code won't be running in production, these don't seem as useful as they do in the project's actual code. (A lot of Generic Object Injection Sink warnings )
Is there a way to have the security plugin ignore certain files other than putting /* eslint-disable */ at the top of every spec file?
The best way I found to deal with this case is based on this answer.
You can override parts of your eslint file in a subfolder. In my case I'm disabling problematic rules from a jest plugin inside my e2e tests folder. Example .eslintrc.js in /e2e-tests/ :
module.exports = {
overrides: [
{
files: ["*.spec.js"],
rules: {
"jest/valid-expect": 0
}
}
]
};
There is three way to ignore files or folders:
1. Creating a .eslintignore on your project root folder with the thing you want to ignore:
**/*.js
2. Using eslint cli & the --ignore-path to specify another file where your ignore rules will be located
eslint --ignore-path .jshintignore file.js
3. Using your package.json
{
"name": "mypackage",
"version": "0.0.1",
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
},
"eslintIgnore": ["*.spec.ts", "world.js"]
}
Official Documentation
On my side, I had issue with Intellij IDEA where eslint was checking files in a folder only dedicated to Typescript (+tslint) which was a pain, so I've picked solution 3.

Resources