preface

githooks

Git Hooks are scripts that are triggered when Git executes a specific event (commit, push, receive, etc.). Similar to “hook functions”, Hooks that are not set to be executed are ignored.

In the.git/hooks directory of the project, there are some sample hook scripts ending with.sample. If you want to enable the corresponding hooks, you can simply manually remove the suffix. (Remove the suffix. Sample of a hook to enable the hook script, which is not enabled by default.)

However, we generally do not change the. Git /hooks files because we use husky.

husky

Husky is a tool for adding hooks to Git clients. After installation, it will automatically add the corresponding hooks to the.git/ directory in the repository; A pre-commit hook, for example, triggers when you perform a git commit.

We can then implement actions such as lint checks, unit tests, code beautification, etc. in the Pre-Commit. Of course, it’s important to make sure that the commands you execute during the Pre-Commit phase are not too slow. Waiting for each Commit is not a good experience either.

lint-staged

Lint-staged, a tool that simply filters out Git code staging files (files that have been added to Git); This is useful because if we do a review of the entire project code, it can take a long time, and if it is an old project, we need to do a code specification review and change the previous code, which can be troublesome, and cause the project to change a lot.

So this lint-staged version, which is a great tool for team projects and open source projects, is a specification and constraint on the code that an individual should submit.

perform

Download package

yarn add husky lint-staged -D

The configuration script

//package.json
"scripts": {
    ...
    "prepare": "husky install",
    "preCommit": "lint-staged"
  },
"lint-staged": {
  "src/**/*.{js,vue}": [
    "eslint --fix",
    "git add"
  ]
 }

Create Husky hooks

Executing the following command will create a pre-commit file under.husky

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

Overall flow route

  1. Commit initiates pre-commit
  2. Hooks to husky
  3. Husky called NPM run preCommit
  4. NPM run preCommit calls lint-staged
  5. Lint-staged calls the lint-staged script inside package.json

I have to say that Husky’s update to version 6 is a lot more cumbersome than before, with the need to register scripts and the addition of.Husky files, which are much more expensive to use than before

PS: Common causes of errors

  1. If the hook is not fired, check to see if the hooksPath path in the.git/config file points to husky

    hooksPath = .husky
  2. .HUSKY/Pre-Commit file created
  3. husky