Using husky with lint-staged in git commit specs

In front-end project development, standardizing git submission information is also a frequently used method. This article will introduce tools such as husky and lint-staged. Using them well will help us to standardize git and team collaboration in project development.

husky

Husky is a git hooksmanagement tool that allows us to manage git hooksscripts more conveniently. It will trigger different hooks when we submit the code, execute different scripts, and help us automate some tasks, such as executing eslintcommands .

First, install husky:

npm install husky -D

Then package.json, scriptsconfigure the autoinstall script in the of the file:

"prepare": "husky install"

After setting up the configuration script, when we execute npm installthe command operation, npm run preparethe command will be executed automatically, that is, husky installthe command , and .huskythe directory will be generated under the root directory of the project, as shown in the figure below:
insert image description here
.huskytwo files will be automatically generated under the directory, of which The script file husky.shrepresents huskythe initial basic configuration of the .

In addition, of course, we can also execute preparethe command , which is also valid:

npm run prepare

Custom configuration directory

.huskyThe directory is generated by default. Of course, we can also customize the file directory of husky configuration, just add parameters to the command, as shown below:

husky install gitHooks/husky

In this way, gitHooksthe directory husky, and the corresponding initialization configuration files will also be automatically generated.

npm life cycle

The execution npm installcommand will automatically execute npm run preparethe command, which is derived from the lifecycle hook of npm.

prepareis a phase in the lifecycle of npma script command action installthat is triggered when executed. When the command
is executed , the corresponding commands will be executed sequentially:install

  • npm 6.x:preinstall -> install -> postinstall -> prepublish -> prepare
  • npm 7+:preinstall -> install -> postinstall -> prepublish -> preprepare -> prepare -> postprepare

After knowing the specific execution sequence, we can add the operations we want at the failed stage, such as the automatic installation of the husky tool above.

For example, we can also add hooks in scripts to unify the package management tools of the project:

"preinstall": "npx only-allow pnpm",

Through the above command, specify the package installation tool of the project as pnpm, if you use npmor yarnto installexecute , an error will be reported, and the three-party package cannot be installed.

Set up git hooks

After the husky installation is complete and the script is configured, we can git hooksset it up.
git hooksAllows us to automatically execute custom scripts when specific commands of git operations occur, to accomplish some additional things.
In our specification of git submission information, the two commonly used stages are: pre-commitand commit-msg:

  • pre-commit: Executed before the code is submitted. Can handle code formatting specifications, etc.
  • commit-msg: Process the message information submitted by the code.

In addition, git hooks have multiple stages that can be enabled when needed, such as the following:

pre-receive: After completing a push from the local version
prepare-commit-msg: After the information is prepared but editing has not yet started
pre-push: Execute
post-update before push: Execute after the workspace update is completed
pre-rebase: In the rebase operation Executed before

pre-commit

In the above introduction, it is mentioned that the husky tool will generate .huskya directory , which stores the basic configuration of husky. To configure git hooks, you have to operate in this directory, you can take the following two ways.

  • First, we can directly create a new file in .huskythe directory : pre-commit, pay attention to the no suffix . Then add the following to the file:
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx eslint src

Among them, npx eslint srcare commands that need to be executed before git submission, and can also be replaced npm run lintwith scriptsscripts like etc.

  • The second, or use a script command to generate the file, execute the following script:
npx husky add .husky/pre-commit "npx eslint src"

After the script is executed .husky, pre-commita file will be automatically generated in the directory, and the corresponding script command will be written: npx eslint src, the content of which is the same as the first method above.

After completing the above operations, when we execute git committhe command , the eslint command will be automatically executed. In addition to eslint, we can also configure other such as stylelint, prettieretc.

commit-msg

messageThe specification of git submission information is also an indispensable part of our project development. This content can help teamwork, version logs, etc.
There are many kinds of agreed-upon specifications in the messagesubmitted specifications, Conventional Commits specificationsuch as, but it is obviously impossible to guarantee the complete and correct execution of the specification only by the specification agreement, so we need auxiliary tools to help us deal with it, for example commitlint.

commitlint

commitlint is currently the most widely used git submission specification verification tool, which can better help us verify messagethe specification .

First, we need to install two dependencies:

npm install @commitlint/cli -D
npm install @commitlint/config-conventional -D

in:

  • @commitlint/config-conventional is a conventional commitsspecification configuration file.
  • @commitlint/cli is the heart of commitlintthe tool .
Configure commitlint

Then, add the .commitlintrc.jsconfiguration file:

You can package.jsonalso add commitlintthe configuration of the field in the file.

module.exports = {
    
    
  extends: ['@commitlint/config-conventional'],
  rules: {
    
    
    'type-enum': [
      2,
      'always',
      [
        'feat', // 新功能(feature)
        'fix', // 修复bug
        'docs', // 修改文档
        'style', // 修改代码格式,不影响代码逻辑
        'refactor', // 代码重构,理论上不影响功能逻辑
        'test', // 修改测试用例
        'build', // 构建或其他工具的变动(如webpack)
        'revert', // 还原以前的提交
        'merge', // 分支代码合并
      ],
    ],
  },
};

The above is a basic command configuration, which mainly defines the content typeof , and the submitted messages typeneed to follow the above configuration.

gitThe Commit Messagehas three parts: Header, Bodyand Footer.
Among them Headeris required, in most of the project development, our git submission information should only contain this part.
HeaderAlso contains three parts: type, scope, subject, where typeand subjectare required.
typeRepresents the type of submitted information, which is mainly regulated in the configuration file above.
subjectRepresents the description content of the submitted information.

Set commit-msg hook

Next, configuration commit-msg hook, through the husky tool introduced earlier, we directly create a new file in .huskythe directory commit-msg, the content is as follows:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit $1

You can also use script commands to automatically generate the file and content:

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'

If you don't use the npx command, it is also possible to use yarn, yarn commitlint --edit $1.

After configuring the hook file, the operation is basically completed and verification can be performed.

Verify git commit

Below, we submit a git message that does not conform to the specification:

git commit -m '测试一下'

At this time, the submission will fail, and the information is as follows:
insert image description here
As shown in the figure above, git submission failed, there is a problem: typeand subjectthe content may be empty.
Because the information is commitlintconfigured type, we also need to add typethe type . For example, the following command can be submitted normally:

git commit -m 'test: 测试一下'

There is a line in the picture above: No staged files match any configured task.
This is the prompt that we have set up lint-staged, but no code file is currently hit, and this prompt will appear.

lint-staged

When pre-commitintroducing , we used npx eslint srcthe command to process code specifications. But it has a problem, that is, every time git submits, it will detect all the files in the entire project src. In many cases, this is not needed. The best way is to detect the newly modified code. The tool
is based on this, and only checks and processes the submitted code files.lint-staged

Install lint-staged:

npm install lint-staged -D

lint-staged needs to add configuration, and generally two methods can be used.

  • Add content directly to the package.json file, as follows:
"lint-staged": {
    
    
  "*.{js,jsx,vue,ts}": [
    "eslint src"
  ]
}
  • Or, add a configuration file, for example lintstagedrc.json, the content is as follows:
{
    
    
  "*.{js,jsx,vue,ts}": ["eslint src"]
}

After configuration, you can modify the pre-commit file and add the following script:

npx lint-staged

At this point, the setting lint-stagedis complete. git commitWhen submitting the code using again, actions such as code checking will be performed first, and it is an incremental code checking .

skip git hooks

If we want to skip commitrelated hooks, we can add --no-verifyparameters to the script command, as shown below:

git commit -m '跳过hook' --no-verify

In this way, all the checks we set up earlier will be skipped, and the code submission action will be completed directly.

Guess you like

Origin blog.csdn.net/jimojianghu/article/details/128792748