In the process of software development, Code Linting is an effective means to ensure Code specification and consistency. In the past, Lint’s work was usually done during Code Review or CI, but this led to a feedback chain of problems and wasted unnecessary time. Therefore, we need to use Git’s Pre Commit hook to place Lint procedures before developers Commit code.
Introduction to the
A brief introduction to these three tools:
prettier
Used to optimize code formatting, such as indentation, Spaces, semicolons, and so onhusky
Can be used to implement a variety of Git hooks. Pre-commit hook is mainly used here. Before committing, run some custom operationslint-staged
Use to perform code checks on files in Git staging
The installation
First, we install husky and Lint-staged into devDependencies of package.json using the following command:
NPM install husky lint-staged prettier –save-dev Or yarn Add husky lint-staged prettier –dev
Configuration package. Json
Append the following code to the package.json file:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"}},"lint-staged": {
"*.{js,vue}": [
"prettier --write"."vue-cli-service lint"."git add"]}}Copy the code
The options under Lint-staged in the example above are commonly configured for VUE projects, and you can configure code checks based on your project’s technology stack.
prettier --write
Will automatically beautify your code formatvue-cli-service lint
Syntax check in vUE projectgit add
Add the changed to file to the staging area
. Prettierrc file
Prettierrc Create a. Prettierrc file in your project root and copy in the following:
{"trailingComma": "es5", // trailingComma" tabWidth": 4, // indent "semi": true, // trailing semicolon "singleQuote": true, // singleQuote" end-of-line": "Lf" // newline}Copy the code
In this way, when committing code at a terminal by typing git commit, Lint will automatically check whether the modified file conforms to the code specification of this project. If the code does not conform to the specification, submission is rejected.
If you want to skip Lint, you can commit using git commit-no-verify.
A link to the
Husky: www.npmjs.com/package/hus… Lint – staged: www.npmjs.com/package/lin… Prettier: www.npmjs.com/package/pre…