每次commit都对代码进行约束校验,配合prettier对代码进行格式化,保证线上代码风格一致
yarn add husky -D
//初始化husky
npx husky-init && yarn
yarn add eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue -D
安装配置lint-staged
yarn add lint-staged -D
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,vue}": [
"eslint --fix",
"prettier --write",
"git add ."
]
},
配置eslint,添加.eslintrc.js
module.exports = {
root: true,
parserOptions: {
parser: "@babel/eslint-parser",
sourceType: "module",
},
env: {
browser: true,
node: true,
es6: true,
},
extends: [
'eslint:recommended',
'plugin:vue/recommended',
'eslint-config-prettier',
'plugin:prettier/recommended',
],
// eslint-plugin-vue
plugins: ['vue', 'prettier'],
rules: {
semi: ['warn', 'always'],
},
};
vscode配置代码自动校验格式化以及修复
//.vscode/settings.json
{
"editor.fontSize": 12,
"editor.formatOnPaste": true,
"editor.fontLigatures": false,
"editor.detectIndentation": false,
"editor.tabSize": 2,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit"
},
"editor.formatOnSave": true, // 开启自动保存
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"javascript.updateImportsOnFileMove.enabled": "always",
"prettier.printWidth": 120,
"prettier.tabWidth": 2,
"prettier.useTabs": false,
"prettier.semi": true,
"prettier.singleQuote": true,
"prettier.quoteProps": "as-needed",
"prettier.bracketSameLine": false,
"prettier.arrowParens": "avoid",
"editor.quickSuggestions": {
"strings": true,
"other": true,
"comments": true
},
"css.lint.unknownAtRules": "ignore",
"scss.lint.unknownAtRules": "ignore"
}