The principle is based on git hook pre-commit implementation, automatically formatting the code in the staging area when the code is submitted.
- Install NPM dependencies
npm i -D husky lint-staged pretty
- Add configuration in package.json
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,json,md}": [
"prettier --write",
"git add"
]
},
"prettier": {
"printWidth": 120
},
Copy the code
- Husky calls pre-commit hooks before committing code, performs Lint-staged formatting if it does not conform to Prettier’s configuration, then tests it with ESLint’s rules, and stops the commit if it does not conform and cannot be fixed automatically. If they pass, the code is added to the stage, and then commit.