为了更好项目质量,对代码和提交信息进行校验配置
校验配置信息: Eslint、 Prettier、 husky、 lint-staged、 commitlint、 stylelint(未配置)
eslint
安装
npm install eslint -D
初始化安装
npx eslint --init
自定义选择配置
- 选择如何使用Eslint
- 仅检查语法
- 检查语法并查找问题 (默认) ✅
- 检查语法、查找问题并强制执行代码样式
- 您的项目使用什么类型的模块?
- JavaScript modules (import/export)(默认) ✅
- CommonJS (require/exports)
- None of these
- 您的项目使用哪种框架?
- React(默认) ✅
- Vue
- None of these
- 您的项目是否使用TypeScript
- Yes ✅
- No(默认)
- 你的代码运行
- brower(默认) ✅
- Node
- 您希望配置文件采用什么格式?
- JavaScript(默认) ✅
- YAML
- JSON
- 是否需要现在安装配置所需依赖
- 使用什么工具安装
自定义配置
rules中配置eslint配置
commitlint
安装
npm install @commitlint/cli @commitlint/config-conventional -D
配置 commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'], // 引入默认的配置规则
rules: { // 配置规则 使用feat: xxxx的方式
'type-enum': [
2,
'always',
[
'upd',
'feat',
'fix',
'refactor',
'docs',
'chore',
'style',
'revert',
],
],
'type-case': [0],
'type-empty': [0],
'scope-empty': [0],
'scope-case': [0],
'subject-full-stop': [0, 'never'],
'subject-case': [0, 'never'],
'header-max-length': [0, 'always', 72],
},
};
prettier
安装
npm install prettier -D
配置 .prettierrc.js
{
//每行最多多少个字符换行
"printWidth": 100,
// tab缩进大小,默认为2
"tabWidth": 4,
// 使用tab缩进,默认false
"useTabs": false,
// 使用分号, 默认true
"semi": false,
// 使用单引号, 默认false(在jsx中配置无效, 默认都是双引号)
"singleQuote": false,
// 行尾逗号,默认none,可选 none|es5|all
// es5 包括es5中的数组、对象
// all 包括函数对象等所有可选
"TrailingCooma": "all",
// 对象中的空格 默认true
// true: { foo: bar }
// false: {foo: bar}
"bracketSpacing": true,
// JSX标签闭合位置 默认false
// false: <div
// className=""
// style={{}}
// >
// true: <div
// className=""
// style={{}} >
"jsxBracketSameLine": false,
// 箭头函数参数括号 默认avoid 可选 avoid| always
// avoid 能省略括号的时候就省略 例如x => x
// always 总是有括号
"arrowParens": "avoid"
}
lint-staged
针对git暂存区的代码进行检测
安装
npm install lint-staged -Dlint-staged版本 > 13 会报错(奇奇怪怪),改为12版本
配置
"lint-staged": {
"*.{js,ts,tsx.css,md}": [
"eslint --fix"
"prettier --write .",
]
}
husky
爱斯基摩狗,更简单的使用git钩子
安装
npm install husky
使用
- 写入script
npm set-script prepare "husky install"初次配置需要手动执行
npx husky install或npm run prepare
- 初始化husky
npx husky init
- 设置commit钩子,用于校验commitlint
npx husky add .husky/commit-msg "npx --no-install commitlint --edit '$1'"
- 设置pre-commit钩子,用于校验暂存区代码
npx husky add .husky/pre-commit "npx --no-install lint-staged"