how to silence warnings about ignored files in eslint - eslint

After setting up eslint and adding some files in the ignore list, every time that eslint is run it produces warnings about files that are ignored:
/path/to/file/name.min.js
0:0 warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override
How can this warning be silenced?

One workaround I know at the moment is --quiet option, which suppresses all warnings. Of course that doesn't make sense if you have "warn" rules in your config.
Another way not to show that warning is to use dir names: eslint src instead of globbing patterns: eslint src/*.

Check if you're running eslint with an unquoted glob argument.
If so, put the glob in quotes.
eslint src/** ❌ Bad (no quotes = OS will expand into many args)
eslint "src/**" ✔️ Good (quotes = a single string argument)
Why?
If you call eslint using a cli glob pattern not in quotes, e.g. eslint src/**, that glob gets expanded into all matching files and passed to eslint as a gigantic list of cli arguments. e.g. eslint path/to/file/name.min.js src/foo.js src/bar.js src/manymore.js .....
So when eslint ignores a file due to your ignore pattern, yet that file was explicitly passed as a command line argument, eslint is warning us
eslint speaking:
"Um, I ignored /path/to/file/name.min.js because of an ignore pattern, but you explicitly passed it to me to lint, so this must not be what you wanted, right?"
But when you pass the glob in quotes, e.g. eslint "src/**", the glob is not expanded to many arguments; rather, it's just a single string argument, and eslint is the one who knows it's a glob but since it takes care of figuring out which files to match it can do so while respecting eslintignore. So there's nothing weird going on that eslint thinks it should warn you about.

You can't and they don't plan on fixing it since they don't consider it a bug. So if you pass in a file that's being ignored them it will tell you it didn't process linting rules because it's ignored: https://github.com/eslint/eslint/issues/5623
We run pre-commit hooks to lint code before committing, so ended up needing to write some additional code to differentiate between actual Warnings and File ignored warnings and only fail linting if an actual warning or error is thrown.

The solution for Lint Staged & Husky errors
// lint-staged.config.js
const { ESLint } = require("eslint");
const removeIgnoredFiles = async (files) => {
const eslint = new ESLint();
const ignoredFiles = await Promise.all(files.map((file) => eslint.isPathIgnored(file)));
const filteredFiles = files.filter((_, i) => !ignoredFiles[i]);
return filteredFiles.join(" ");
};
module.exports = {
"*.{js,ts}": async (files) => {
const filesToLint = await removeIgnoredFiles(files);
return [`eslint --max-warnings=0 ${filesToLint}`];
},
};
If the file is ignored by ESLint (i.e. in .eslintignore), this snippet filters the file and does not pass it through the ESLint CLI.
ref: Testing Library - Aug 2022

I found the REAL answer here:
https://github.com/eslint/eslint/issues/5623
The problem in my case was in the way I called eslint. I used eslint src/* but it should be eslint src/. (Or in your case it might be eslint . instead of eslint *)
The reason why you get the warning is that by using the star, you are telling the eslint that you want to lint EVERY single file which does not make sense if you ignore some files. So by omiting the star you are making the eslint to decide what to lint and it will skip the ignored files without any warning.

Eslint throws this warning on telling it to lint a file, at the same time as having the file ignored. src/* is actually passing every file single file uniquely, while only passing src would let eslint ignore the files without warnings
If you are using lint-staged, it will pass every single staged file that matches the lint-staged regex. If matching, and you put it inside ignore, eslint gets confused and outputs a warning
"lint-staged": {
"*.{ts,tsx,js}": [ // <-- this regex needs to be changed to not match your files
"eslint --fix --max-warnings 0 --ignore-path '.eslintignore' --plugin tsc --rule 'tsc/config: [2, {configFile: \"./tsconfig.json\"}]'",
"prettier --ignore-path .eslintignore --write"
],
"*.js": "eslint --cache --fix",
"*.{js,css,md}": "prettier --write"
},
For me, I just wanted to exclude some js files, so I just removed the js matching inside "*.{ts,tsx,js}"

try with --ext. In my case, I replaced matching from:
eslint modules/**/*{js,vue}
to:
eslint --ext .js,.vue .
Warnings with File ignored because... are gone, but others warnings remain.

My solution for Next.js next lint and a .lintstagedrc.js file. This removes the files that have that warning from the final string of files to lint.
// .lintstagedrc.js
const path = require("path");
const ignorePaths = ["types/global.d.ts", ".lintstagedrc.js"];
const buildEslintCommand = (filenames) => {
return `next lint --fix --max-warnings=0 --file ${filenames
.reduce((files, file) => {
const pathToFile = path.relative(process.cwd(), file);
if (!ignorePaths.includes(pathToFile)) files.push(pathToFile);
return files;
}, [])
.join(" --file ")}`;
};
module.exports = {
"*.{ts,tsx,js,jsx}": [buildEslintCommand],
"*.{ts,tsx,js,jsx,css,scss,md}": "prettier --write",
};

Related

no-unused-expressions error in package.json

I am adding a linter to my big existing project. I have enabled "error" for no-unused-expressions. I am using lint-staged to run the linter upon git committing.
my .lintstagedrc.js:
module.exports = {
'*': ['eslint --ext .js,.jsx,.ts,.tsx,.graphql --fix .', 'npx prettier --ignore-path .eslintignore --write'],
}
When trying to git commit (staging includes changes to package.json)
I get:
/Users/myuser/myproject/package.json
1:1 error Expected an assignment or function call and instead saw an expression no-unused-expressions
And my normal-looking package.json:
{
"name": "myproject",
"private": true,
"description": "myproject description",
...
Since json is such a tightly defined format, I have a high degree of confidence it is formatted properly. This leads me to believe it is an eslint setting of some sort. I can't even really be sure why this no-unused-expressions rule would be looking at a json file.
Not sure where to begin diagnosing this one.
The '*' in your .lintstagedrc.js means all files will be checked by eslint, regardless of extension. What you probably want to do is this:
module.exports = {
'*.{js, jsx, ts, tsx, graphql}': ['eslint --fix', 'prettier --ignore-path .eslintignore --write'],
}
By calling eslint on package.json you interpret it as a JavaScript/TypeScript file (based on your configuration). Any JSON file is also a valid JavaScript file that contains a single value that is not assigned to anything, which is called an unused expression and should not normally occur in your code.

Can't enable no-console using eslint cli

I'm using eslint, and in my configuration file I have "no-console": "off".
I want to turn it on for my CI system, so I've been using the command line (vue cli syntax):
vue-cli-service lint --rule '"no-console": "error"'
This doesn't work.
However, if I invert things (set error in the configuration, and pass off as a flag) it does work.
Anyone know why?
EDIT: it should probably look like vue-cli-service --rule 'no-console: 2'
PS: "error" may be working too I guess.
You can make a config in a lot of places but the usual one is probably .eslintrc.js in which you can write
module.exports = {
[...]
// add your custom rules here
rules: {
"no-console": "off",
},
}
As shown here: https://eslint.org/docs/rules/no-console
This one should work but it always depend on how your project is setup too.

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

How to disable autofix for specific rules in eslint using CLI?

I want to be able to disable the rules that --fix fixes when running eslint in a console for a repo. The reason for this is because --fix leads to undesirable behavior for our jsdoc eslint rules. It creates invalid or sometimes empty jsdoc in our project- which typically leads to even more eslint rules (due to our configuration) and leads to tons of manual fixing or removal.
I want to just run --fix without it touching any jsdoc rules so that I can complete jsdoc manually- while eslint fixes all the rest of the rules.
I came across this SO question- but package mentioned in the answer does not support non-core plugins.
ESLint autofix ignore rule
Is there anything I can do short of modifying my eslintrc file every time I run the linter or using vscode for linting and modifying the config for the web editor instead? Its not a big deal for newer files- but linting legacy files is a chore when there's hundreds of spacing errors that I can't automatically fix easily.
Using an .eslintrc.js file you can do something like this:
const isFixMode = process.argv.includes('--fix');
const config = {
rules: {
'no-console': 'error',
...(isFixMode && {
'no-console': 'warn',
}),
},
};
module.exports = config;
Technically, that already exists, right? If a user wants to avoid auto-fixing a particular rule, they can use:
eslint somedir --fix --rule "somerule: 0"
Or, if they want to whitelist a set of rules, they can use &nbps --no-eslintrc and specify rules directly or use --config and point to a particular config that they want to use for fixes.
Ok here’s another idea. Convert you .eslinrc file into .eslintrc.js. This will allow you to programmatically set eslint config.
Then you could use the commander library to detect the —fix flag and set a Boolean to determine which eslint rules you would like to disable.
What worked best for me was setting the rule to warn and afterwards run.
eslint . --fix --quiet
It is not an error anymore, but better than getting my code broken by a erroneous fixer.

Husky/lint-staged is it possible to exclude/ignore file?

Is it possible to exclude/ignore a file when using Husky/lint-staged hooks?
Looking through the docs atm but not having any luck finding anything on this.
Was hoping there was something like an
/*ignore*/
tag that I could add.
To make lint-staged ignore certain files that were causing formatting issues.
Any thought on this greatly appreciated :)
Ended up adding
.prettierignore
file.
Not ideal but seems to do the job ok.
I finally found out how to do this (at least as of lint-staged v11.1.2)
In package.json:
"lint-staged": {
"!(path/to/excluded/dir/**/*)*.ts": [
"eslint --fix",
"prettier --write"
]
}
Note the globstar pattern is within the negation pattern and not outside it. This ensures that subdirectories are also excluded.
While configuring lint-staged in package.json or If you're using any other IDE, in order to ignore/exclude files by lint-Staged and husky hooks, you can add an "ignore" key in the lint-staged object to make it ignore whatever packages or files you want to ignore. Use the following extensible syntax:
{
"lint-staged": {
"linters": {
"src/**/*.js": ["formatter --write", "git add"],
},
"ignore": ["node_modules", "dist", "package-lock.json"] }
}
Just add the target pattern to 'linters' object and all the ignored files which you might be adding previously to .prettierignore to "ignore" key of lint-Staged object. And there you go!
If anyone still looking, take a look at this https://github.com/okonet/lint-staged#filtering-files It has good examples.
Filtering files
Linter commands work on a subset of all staged files, defined by a glob pattern. `lint-staged´ uses micromatch for matching files with the following rules:
If the glob pattern contains no slashes (/), micromatch's matchBase option will enabled, so globs match a file's basename regardless of directory:
"*.js" will match all JS files, like /test.js and /foo/bar/test.js
"!(*test).js". will match all JS files, except those ending in test.js, so foo.js but not foo.test.js
If the glob pattern does contain a slash (/), it will match for paths as well:
"./*.js" will match all JS files in the git repo root, so /test.js but not /foo/bar/test.js
"foo/**/\*.js" will match all JS files inside the/foodirectory, so/foo/bar/test.jsbut not/test.js
So I've been trying to find an answer for this for an entire day and looking at all the forums suggested that they use minimatch for glob check which might have been correct for older versions but they use micromatch for new version and to solve this issue we can use their pattern to exclude certain directories
So in your .lintstagedrc you can add the following pattern to avoid certain folders
{
"*.{json,md,html,scss}": ["prettier --write", "git add"],
["**/!(folder1|folder2)/*.ts"]: ["tslint --project tsconfig.json -c tslint.commit.json --fix", "prettier --write", "git add"]
}
So the glob here is an actual array and make sure not to pass this array within a string else it won't recognize the patterns also do not include **/*.ts the reason being lint-staged automatically converts this into a matchBase comparision if it finds / in the pattern so including this will also match against your folder1|folder2 files.
can fix in three ways:
.lintstagedrc.js
.prettierignore
lint-staged.config.js
more info : https://github.com/okonet/lint-staged/issues/797

Resources