Improving Code Review Efficiency with Husky

During code review, code style is one of the review criteria. Reviewing code style involves a certain amount of work.

To reduce the workload of code review, why not standardize code style before committing?

This way we can save a lot of time during code review and spend it on more meaningful things.

Git Hooks

Git provides hooks — mechanisms to trigger other programs when operations like code commit, push, etc. occur.

I won’t go into detail on how to use them here.

Interested readers can refer to the documentation: https://git-scm.com/docs/githooks

Husky

If you’ve read the githooks documentation, did you find it a bit tedious?

Here’s a tool called husky that can solve your problem.

Installation

npm install husky --save-dev

Then modify package.json to add the configuration:

{
  "husky": {
    "hooks": {
      "pre-commit": "eslint ."
    }
  },
}

If you only have eslint installed locally, use the following configuration:

{
    "lint-staged": {
    "src/**/*.js": [
      "node_modules/.bin/eslint"
    ]
  },
}

Finally, try a Git commit and you’ll get feedback quickly:

git commit -m "this is a commit"

This way, we can verify whether our code passes lint before committing.

For projects that have never used ESLint before, suddenly introducing such a tool might mean you’d have to format all files according to ESLint rules. That would be crazy, right?

lint-staged

Let me recommend another tool that enables ESLint to only check the files in the current commit. This allows us to progressively improve our code quality.

Installation

npm install lint-staged --save-dev

Modify package.json configuration:

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.js": "eslint"
  }
}

Run Custom Commands Before lint-staged

This is something I really like — it gives us more flexibility.

Modify package.json configuration:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "src/**/*.js": ["eslint --fix", "git add"]
  }
}

Perfect, everything looks great~

Article Link:

/en/archive/husky-code-review/

# Related Articles