reference
The module used
- The prettier code formatting module
- A husky Git hook that executes commands in git hooks
- Lint-staged files that have been temporarily stored in Git are lint-checked
- Eslint code detection tool
1, the prettier
Add configuration file. Prettierrc, JSON file cannot be commented, so I use JS file (prettier.config.js or.prettierrc.js)
module.exports = {
printWidth: 200.// The number of characters in a line. If more than 80 characters are added to the line, the default value is 80
tabWidth: 2.// A TAB represents several Spaces. The default is 80
useTabs: false.// Whether to use TAB for indentation. The default value is false, indicating that Spaces are used for indentation
semi: true.// Whether to use semicolons on line bits. Default is true
singleQuote: true.// Whether to use single quotation marks for strings. The default is false. Use double quotation marks
trailingComma: 'none'.Tail / / whether or not to use commas, there are three optional value "< none | es5 | all >"
bracketSpacing: true.{foo: bar} {foo: bar}
arrowParens: 'avoid'.// Avoid parentheses for arrow functions that have only one argument
jsxBracketSameLine: false.// Use single quotes in JSX
};
Copy the code
Problematic configuration item: parser: ‘Babylon’
Prettier uses multiple Parser for different languages, compiling JS as Babylon by default. Babylon is the compilation tool for Babel6, renamed @babel/ Parser in Babel7. When submitting automatic formatting code error Couldn ‘t resolve parser “Babylon”, may be inconsistent version, so change to’ Babel ‘, but will quote vue grammatical errors, but after the deletion of the configuration can normal formatting code.
Webstorm supports Prettier as the default formatter, as shown below
2, husky
See husky usage summary
- The installation
npm install husky --save-dev
Copy the code
- Package. json adds the script
"scripts": {
"prepare": "husky install"
}
Copy the code
- Generated in the project after running
.husky
folder
npm run prepare
Copy the code
- Add hooks
npx husky add .husky/pre-commit "lint-staged"
Copy the code
A shell script named pre-commit will be added to the. Husky folder
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
Copy the code
NPX: Command not found NPX: Command not found NPX: Command not found NPX: Command not found NPX: Command not found
PATH=$PATH:/usr/local/bin:/usr/local/sbin
Copy the code
3, lint – staged
Add configuration in package.json
"lint-staged": {
"src/**": [
"prettier --config .prettierrc --write"."eslint --fix"."git add" // This is to submit a file that has been automatically formatted]}Copy the code
The whole process
- Git commit triggers a pre-commit script defined by Husky
- Lint – staged operation
- Automatically formatting code based on configuration items, then checking ESLint and triggering a COMMIT if it works
Husky + Lint-staged can do many automated things like commitlint, unit testing, etc