Skip to content

Instantly share code, notes, and snippets.

@leothorp
Last active October 29, 2023 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leothorp/85f8bbe6d9f4a117c40165e99a656598 to your computer and use it in GitHub Desktop.
Save leothorp/85f8bbe6d9f4a117c40165e99a656598 to your computer and use it in GitHub Desktop.
JS pre-commit hook (Prettier, linting). Noticeably faster than lint-staged.
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"
set -e
bin_dir="node_modules/.bin"
echo "running pre-commit script..."
# --diff-filter used to exclude deleted files
prettier_staged_files=$(git diff --cached --name-only --diff-filter="ACMRTUXB")
eslint_staged_files=$(git diff --cached --name-only --diff-filter="ACMRTUXB" -- *.{tsx,ts,js,jsx})
prettier_length=${#prettier_staged_files}
eslint_length=${#eslint_staged_files}
if [ $eslint_length -gt 0 ]
then
$bin_dir/eslint --no-error-on-unmatched-pattern --ignore-path .gitignore --fix --ext .jsx,.js,.ts,.tsx --cache $eslint_staged_files
git add $eslint_staged_files
fi
if [ $prettier_length -gt 0 ]
then
$bin_dir/prettier --ignore-unknown --no-error-on-unmatched-pattern --ignore-path .gitignore --cache --write $prettier_staged_files
git add $prettier_staged_files
fi
@leothorp
Copy link
Author

leothorp commented Nov 30, 2022

One-liner to install in a repo. Prereqs: Husky, Prettier, ESLint.

npx husky add .husky/pre-commit "" &&\ 
curl -s https://gist.githubusercontent.com/leothorp/85f8bbe6d9f4a117c\
40165e99a656598/raw/1516ddaeebaa56ee42331e16b42bf00eab66b4\
d8/fast-js-pre-commit | sed -e 1,2d >> .husky/pre-commit &&\
npx husky install

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