preface
I don’t know if you’ve ever been in a situation where you feel uncomfortable looking at the front-end code of other members of your team, because your habits and editor are different and your code style is different. That’s a good choice for reading unified formatting team code.
Install dependencies
Ultimately, we want to do a style check before committing git and only commit if the formatting passes, otherwise an error will be reported. For code style, the popular prettier, which arbitrarily formats code according to a configuration file, agrees among the team partners. Husky provides a list of hooks for git commits. In this case, we’ll use the pre-commit hook.
yarn add husky prettier -D
Copy the code
Example Configure the formatting rule for prettier
Prettierrc we can use the. Prettierrc file or add configuration in the package.json file, but the. Prettierrc file is recommended here:
{"arrowParens": "always", // Whether to use () "bracketSpacing": false, // {foo: xx} or {foo: xx} "jsxSingleQuote": True, // whether to use single quotation marks "jsxBracketSameLine": false, "semi": true, // whether to use single quotation marks "tabWidth": 2, // use 'trailingComma' : 'es5'}Copy the code
Configure husky hooks
Huskyrc, which is a separate configuration file that we’re using here, goes directly to the configuration code
{
"hooks": {
"pre-commit": "lint-staged" // pre-commit,提交前的钩子
}
}
Copy the code
Lint-staged dependencies need to be installed separately as well, which is what you should do before committing
yarn add lint-staged -D
Copy the code
Lintstagedrc configuration file as follows:
{ "src/**/*.js? (x)": [ "prettier --write", "eslint --fix", "git add" ], "src/**/*.{css,less,scss}": [ "stylelint --fix", "git add" ] }Copy the code
Prettier is used for formatting files, then esLint fixes them, and if esLint is installed, then commit git.
Afterword.
Of course, if you want to format code locally, you can also find the corresponding prettier plug-in in your own editor, so you won’t expand it here. And we can add a set of commands to the package.json script object to format the code:
"eslint": "prettier --check --write src/**/*.js? (x)"Copy the code
reference
- Code style uniformity: Use Husky, Prettier, ESLint to automatically format and inspect code when it is submitted.
- Use ESLint+Prettier to unify front-end code styles
- Prettier vscode + prettier