As developers, we have all felt the sting of build and test failures after pushing our code. Iāve found that having a pre-deployment checklist can save a lot of headaches. In this article, we will set up Husky to automate crucial checks before committing and pushing code using the pre-commit and pre-push hooks in a Node.js project. This would help us catch potential issues early in the development process.
Now, I know what youāre thinking arenāt there CI/CD pipelines for this kind of thing? And youāre right, there are. But hereās my take: why push code thatās destined to break when you can catch those pesky errors before they ever leave your machine? Itās like giving your code a quick once-over before it heads out the door. Trust me, your future self (and your team) will thank you.
To get started, create a new directory or clone an existing repository
mkdir website # creates a new folder
or
git clone repository # clones a git repository
cd website #change directory
npm init -y # Initializes a new Node.js project with default settings
We also need to initialize git (assuming it's already a git repository; there would be no need for this)
git init # initializes a new GitHub repository
Once these steps are completed, install Husky as a dev dependency; hence the -D.
We donāt want to push our node_modules and environment variable (.env) files, so we create a .gitignore file and add node_modules to it.
PS: You can go ahead and add files you don't want to push online, like your environment variable.
npm install husky@latest -D # installs husky as dev dependencies
touch .gitignore && echo node_modules >> .gitignore # create a new file called .gitignore and writes node_modules into the file
Once the previous steps are completed, We can go ahead and initialize Husky
npx husky init # initializes husky in the project
Husky creates a new .husky directory
Inside this directory, we are going to create our two new hooks: pre-commit and pre-push.
touch .husky/pre-commit && touch .husky/pre-push # creates 2 new files inside the .husky directory
Inside the pre-commit hook file, we are going to run our test
and in the pre-push, we want to run our application build
Note: This is just an example, and in your case, you can decide to lint your commit messages, code, run tests, etc. upon committing or pushing.
You can also implement this using Git pre-commit and pre-push hooks. Check out the article below by Benjamin Chibuzor-Orie.
How to run tests automatically on each push to the repository
By setting up Husky with these pre-commit and pre-push hooks, youāve added an extra layer of quality assurance to your development process. This simple setup can save you time and prevent embarrassing mistakes from making their way into your repository. Remember, you can customize these hooks to fit your projectās specific needs. Happy coding!