CI using Git pre-commit hooks with npm and husky
Table of Contents
CI using Git pre-commit hooks with npm and husky
- Git pre-commit hooks allow you to run scripts before a commit is made, which can be useful for running tests, linters, or other checks to ensure code quality. npm husky is a popular tool that makes it easy to manage Git hooks in JavaScript projects.
Install npm via fnm
For more details, see fnm - Fast and simple Node.js version manager.
sudo apt install -y curl unzip
curl -fsSL https://fnm.vercel.app/install | bash
fnm --version
Install latest stable Node.js:
# Install latest stable Node.js
fnm install --lts
# Use it (current shell session only)
fnm use --lts
# Set as default (default for all shell sessions)
fnm default lts-latest
# Confirm
node --version
npm --version
Setup Project
cd your-project
# Initialize npm project
npm init -y
# Install husky
npm install husky --save-dev
# Initialize husky (creates .husky/pre-commit and adds prepare script)
npx husky init
# Edit .husky/pre-commit to add your hook command
echo "npm test" >> .husky/pre-commit
And add the test script manually to package.json:
"scripts": {
"prepare": "husky",
"test": "echo \"Running tests...\" && exit 0"
}
Now, whenever you try to commit changes, the pre-commit hook will run npm test before allowing the commit to proceed. You can replace npm test with any command you want to run as part of your pre-commit checks.