Husky is a popular tool used in software development projects to manage Git hooks. Git hooks are scripts that run automatically every time certain important actions occur in a git repository, such as committing or pushing code. Husky simplifies the management of these hooks, ensuring that code commits meet the project's standards before they are pushed to the repository. This guide explores how to set up and use Husky with npm, the Node.js package manager.
Understanding Husky and npm
Husky: Leverages Git hooks to enforce code quality standards and run tests before commits and pushes, ensuring that only quality code is added to the repository.
npm (Node Package Manager): npm is the default package manager for Node.js and is used for managing project dependencies.
Setting up Husky with npm
To integrate Husky in your Node.js project, you'll need to follow several steps to ensure it is correctly set up and configured.
Prerequisites
- Node.js installed in your system
- A Git initialized project
- npm available in your project
Step 1: Install Husky
To install Husky, you need to run the following command in your project's root directory:
npm install husky --save-dev
This command installs Husky as a development dependency in your project.
Step 2: Enable Git hooks
After installing Husky, you need to configure it to handle your Git hooks:
npx husky install
This command sets up Husky in your project, creating a .husky/
directory where your hooks will be stored.
Step 3: Add hook scripts
You can add Git hooks using Husky by creating a script in the .husky/
directory. For example, to add a pre-commit hook that runs linting before every commit, you could do the following:
npx husky add .husky/pre-commit "npm run lint"
This command creates a pre-commit
hook that runs the npm run lint
command before each commit.
Common issues and troubleshooting
Husky npm not found: If you encounter an error saying Husky or npm is not found, ensure that Node.js is properly installed and that your project directory is correct. Running
npm install
might resolve missing dependencies.Hooks not running: Make sure Husky is installed and enabled. You might need to re-run
npx husky install
if the hooks do not trigger as expected.
Advanced usage of Husky
To customize Husky further or handle more complex workflows, you can edit the hook scripts directly in the .husky/
directory. You can also use Husky to integrate with other tools like ESLint, Jest, or any other scripts that should run before your code is committed to the repository.
For more reading see the official Husky documentation.