All You Need to Know About Husky for Efficient Git Hooks Management

Introduction to Husky

Husky is a modern and efficient tool for managing Git hooks, allowing developers to automate tasks and improve their workflow. It provides an easy way to set up and configure hooks, ensuring that code meets quality standards before being committed.

Setting Up Husky

To install Husky, you need to have Node.js and npm installed. Use the following command:

npm install husky --save-dev

Enabling Hooks

Initialize Husky to create a .husky directory in your project:

npx husky install

Example: Pre-commit Hook

Create a pre-commit hook to run linting:

npx husky add .husky/pre-commit "npm test"

Now whenever you make a commit, the specified tests will run.

Useful Husky API Examples

Adding a Pre-push Hook

To add a pre-push hook, run:

npx husky add .husky/pre-push "npm run build"

Running Custom Scripts

If you want to run a custom script before committing, add it to your package.json:

 {
  "scripts": {
    "precommit": "echo 'Running pre-commit tasks'"
  }
} 

Then run:

npx husky add .husky/pre-commit "npm run precommit"

App Example with Husky

Let’s create a small app to demonstrate Husky in action. First, initialize a new Node.js project:

 mkdir husky-demo cd husky-demo npm init -y 

Install some necessary packages:

 npm install husky eslint --save-dev 

Initialize Husky:

npx husky install

Add a pre-commit hook to run ESLint:

npx husky add .husky/pre-commit "npx eslint ."

Create an ESLint configuration file:

 {
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaVersion: 12,
    "sourceType": "module"
  },
  "rules": {
    "quotes": ["error", "single"],
    "semi": ["error", "always"]
  }
} 

Now, every time you commit changes, ESLint will run to ensure code quality.

Hash: 09e28e9c5875ef3b2b7463e1c9adc3cefbd35af73283f9f9281dc9b8c48f9524

Leave a Reply

Your email address will not be published. Required fields are marked *