'Run eslint "ONLY" on the staged files
I am trying to use a pre-commit hook to detect eslint errors before commit happens. I am using husky and lint-staged. But it runs the lint command for all the files in src and not on staged files only. Here is my package.json file.
"scripts": {
"test:ci": "cross-env CI=true react-scripts test --bail --passWithNoTests",
"lint": "eslint src/**/*.{js,jsx}",
"lint:fix": "eslint . --fix",
"precommit": "npm run lint && npm run test:ci"
}
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": [
"npm run precommit"
],
"*.jsx": [
"npm run precommit"
]
}
Is there any way so that it works ONLY on staged files and not on other files present in the directory?
Solution 1:[1]
With husky v7/lint-staged v11.2.0 - the staged files will simply by added onto the end of your command, separated by spaces. If you have a .husky/pre-commit file which calls npx lint-staged, and then you have a lint-staged config like so:
{
'*.js': [
'eslint'
]
}
And you modify src/foo.js and src/bar.js, the command that will be run is:
eslint src/foo.js src/bar.js
Doesn't matter what command you have inside of your lint-staged config. Files are just added onto end of command, separated by spaces.
Solution 2:[2]
According to this lint-staged example, I implemented that in order to lint only staged files (takes like 5 secs) except when there are more than 5 staged files, it checks all the repo (can take more than 1 min):
- Upgrade
lint-stagedpackage to the latest version - Add a
.lintstagedrc.jsfile at the root of your repo. It could contain something like this:
module.exports = {
'**/*.js?(x)': (filenames) =>
filenames.length > 5 ? 'eslint --ext .js,.jsx . --ignore-path .gitignore --fix .' : `eslint ${filenames.join(' ')} --fix`,
"*.json": [
"prettier --write"
]
}
- Remove your old "lint-staged" command from the
package.jsonfile
Solution 3:[3]
"husky": {
"hooks": {
"pre-commit": "lint-staged"
},
},
"lint-staged": {
"*.js": [
"eslint src/**/*.{js}",
"cross-env CI=true react-scripts test --bail --passWithNoTests",
"git add"
]
},
Solution 4:[4]
With the ESLint CLI you have a help parameter npx eslint -h, --help or you can check the CLI docs at the official ESLint docs page/CLI. There's a section related to caching, so that ESLint only looks at files that have been changed.
Caching:
--cache Only check changed files - default: false
--cache-file path::String Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
--cache-location path::String Path to the cache file or directory
--cache-strategy String Strategy to use for detecting changed files in the cache - either: metadata or content - default: metadata
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Devin Rhode |
| Solution 2 | PestoP |
| Solution 3 | hendrixchord |
| Solution 4 | lua_python_java |
