DEV Community

Eray Kaya
Eray Kaya

Posted on

Leveraging Pre-commit Hooks with Husky and Lint-Staged

There exists a debate over the necessity of pre-push or pre-commit hooks. Critics argue that developers shouldn't be limited in their ability to push code to the codebase and that code checks should instead be executed during the PR review process. However, pre-commit hooks, such as those with lint-staged, can provide substantial benefits, particularly for new teams starting on a project. Before diving into the of Github actions or anything like that, these hooks offer a straightforward way to ensure consistent code quality.

To illustrate this, let's begin by installing Husky in our project:

yarn add husky -D

Next, we need to add a prepare script to our package.json file. This script allows every team member to run it once, setting up the necessary hooks for their local development environment. The prepare script should look like this:

"prepare": "husky install"

After adding the script, run yarn prepare to set up Husky. Subsequently, create a pre-commit hook with the command npx husky add .husky/pre-commit "yarn lint". This command creates a hook that runs every time a commit is made, although we'll modify it shortly to run only on modified files.

Once the above steps are completed, you should see a .husky directory in your project root.

Next, let's introduce lint-staged:

yarn add lint-staged -D

Lint-staged is a tool that allows you to run scripts on files staged in git. We use it here to run our linter only on files that have been changed in the commit.

To configure lint-staged, we add the following to our package.json file:

"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "eslint",
    "prettier --write"
  ]
},
Enter fullscreen mode Exit fullscreen mode

Then, add a script to the package.json file that will call lint-staged:

"pre-commit": "lint-staged"

Finally, modify the .husky/pre-commit file to use yarn pre-commit instead of yarn lint. With this change, the linter will only run on files modified in the commit.

In conclusion, pre-commit hooks using Husky and lint-staged offer an efficient way to maintain code quality across a team. These tools ensure that only consistent, well-formatted code is committed to the codebase, thereby simplifying the PR review process.

Top comments (0)