-
-
Save dahjelle/8ddedf0aebd488208a9a7c829f19b9e8 to your computer and use it in GitHub Desktop.
#!/bin/bash | |
for file in $(git diff --cached --name-only | grep -E '\.(js|jsx)$') | |
do | |
git show ":$file" | node_modules/.bin/eslint --stdin --stdin-filename "$file" # we only want to lint the staged changes, not any un-staged changes | |
if [ $? -ne 0 ]; then | |
echo "ESLint failed on staged file '$file'. Please check your code and try again. You can run ESLint manually via npm run eslint." | |
exit 1 # exit with failure status | |
fi | |
done |
Thanks @nemesarial! This works like a charm
This does not lint "only staged changes" it lints each file that is changed. Which is annoying because it can block your commit for stuff that isn't even in the commit! Eslint should just have a --diff
options like flake8
There is an cleaner way to accomplish this, with husky:
// package.json
...
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"prettier --write",
"eslint --ext .ts,.tsx,.js --fix"
]
},
LGTM, but maybe eslint
should be run before prettier
.
Note: If you use ESLint, make sure lint-staged runs it before Prettier, not after.
ref: https://prettier.io/docs/en/install.html#git-hooks
},
@aperkaz
Where exactly i need to place above lines inside package.json file.
@Naveen9453 after the dependencies section is a good place, although I tend to locate it at the end of the file. No strict placement requirements though.
package.json
configuration of husky no longer works, by design.
Thank you to OP -- very useful. I adapted and my
lint-staged.sh
file looks like this:Benefits are:
npx
allows running local or globaleslint
eslint
limits this to a single run -- soeslint
only has to start up once, and not once for every fileeslint
by adding arguments to shell command. ie../lint-staged.sh --fix