Skip to content

Instantly share code, notes, and snippets.

@dahjelle
Created July 13, 2016 16:48
Show Gist options
  • Save dahjelle/8ddedf0aebd488208a9a7c829f19b9e8 to your computer and use it in GitHub Desktop.
Save dahjelle/8ddedf0aebd488208a9a7c829f19b9e8 to your computer and use it in GitHub Desktop.
Pre-commit hook for eslint, linting *only* staged changes.
#!/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
@swateek
Copy link

swateek commented May 9, 2022

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

this worked for me & I also took @zhyd1997's suggestion

@Naveen9453
Copy link

  },

@aperkaz
Where exactly i need to place above lines inside package.json file.

@aperkaz
Copy link

aperkaz commented Jul 19, 2023

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

@timheilman
Copy link

package.json configuration of husky no longer works, by design.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment