NPM package which you should add to almost any git repo😺

NPM package which you should add to almost any git repo😺

·

4 min read

What are Git Hooks?

These are scripts that run on your repository at specific event.

How is this useful?

You can run a specific task before making any commit.

Set a rule for commit messages.

Basically anything you can write inside a script. So endless possibilities.

Let's explore few possibilities that you can take away.

This article is targeted for Javascript and requires package.json. You can get an idea and explore more for other developments.

Meet Husky😺

Install it using:

npm install husky --save-dev

Inside package.json, add

"husky": {
    "hooks": {
      "pre-commit": "npm test" // any command here
      }
}

This will run test cases before every commit. If test cases fail, commit will also fail. This is perfect if you made some changes and it might have broken your code.

You can replace npm test with npm build or any other command based on your use case.

pre-commit defines when to run your command. It could be post-commit or pre-push, and many more. You can refer this link for more examples. You can also open hidden .git folder inside your repo and see a hooks folder there. It will contain all the hooks inside it.

lint-staged🥰

Sometimes, we want to do certain operations on staged files only. Many of us already use tools like prettier and eslint to follow certain guidelines and give a uniform look to our code (If not, please check that out. I will soon draft an article on that as well).

lint-staged can help you automatically format your code before commit, or check for empty commit requests, and verify eslint rules. Also, it handles staged files only, so we don't have to worry about other code that is still in development.

For example: Syntax of your code is wrong, or there's a variable in your code which you haven't used anywhere. You will not be allowed to commit your code.

Let's see how to achieve this.

Once you have Husky installed, run

npm install --save-dev lint-staged

Add this line inside pakage.json

// "husky": {
//        "hooks": {
//            "pre-commit": "npm test && lint-staged"
//        }
//    },
"lint-staged": {
        "*.{js, test.js}": [  // specify which files to check
            "prettier --write",  // prettier format
            "eslint --fix"  // check eslint and fix auto fixable eslint rules
        ]
    }

âš  Make sure you have configured eslint and prettier.

If you see the commented-out section, I've configured Husky to run test cases as well as call lint-staged. Lint-staged will in-turn call your scripts/commands. Here, just for example, we have used prettier and eslint commands.

Now you can forget about running test cases before every commit, and your code is automatically kept in sanitized format.

Also read:

Improve your git commit message quality using Husky. For more information, click here.

Â