前言
对于代码监测流目前大多数分为两种,服务端校验和本地提交校验,这里简单阐述下优缺点 服务端校验通过CI持续集成的方式做lint一般这种方式反馈链路比较长(一般CI不仅仅之做lint,如果lint失败则需要重新集成),本地提交校验可以在commit code时做校验这样减少反馈链路较少等待时间(本地校验会有人为干预的风险),本文主要针对本地提交commit阶段做校验
安装
npm install eslint husky lint-staged @commitlint/config-conventional @commitlint/cli -D
复制代码
- Eslint - 代码规范
- Husky - 提供git钩子
- Lint-staged - 获取暂存区文件
- @commitlint/config-conventional @commitlint/cliEslint - commit提交规范
配置
项目
- Eslint 配置
{
"root": true,
"env": {
"browser": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:vue/strongly-recommended"],
"parserOptions": {
"ecmaVersion": 2018
},
"globals": {
// [writable]可以重写 [readonly]只读属性
"Swiper": "readonly",
"ZIROOMCommon": "readonly",
"$": "readonly"
},
"rules": {
"no-mixed-spaces-and-tabs": "off", // 禁止空格和 tab 的混合缩进
"no-dupe-keys": "error", // 禁止对象字面量中出现重复的 key
"no-undef": "error", // 禁用未声明的变量
"no-empty": "error", // 禁止出现空语句块
"no-unused-vars": "warn", // 禁止出现未使用过的变量
"no-console": "warn", // 禁用 console,
"no-useless-escape": "error", // 禁用不必要的转义字符
"no-prototype-builtins": "off",
// 强制每行的最大属性数
"vue/max-attributes-per-line": [
"warn",
{
"singleline": 2,
"multiline": {
"max": 1,
"allowFirstLine": true
}
}
],
"vue/require-v-for-key": "error", // 需要v-bind:key用v-for指令
"vue/no-use-v-if-with-v-for": [
"error",
{
"allowUsingIterationVar": true
}
], // 禁止在与v-for相同的元素上使用v-if 请用计算属性代替
"vue/no-unused-components": "warn", // 禁止出现未使用过的组件
"vue/require-valid-default-prop": "error", // 强制props默认值有效
"vue/valid-v-for": "error", // 检查每个v-for指令是否有效 【自定义组件使用v-for,则必须加 :key标注】
"vue/no-side-effects-in-computed-properties": "error", // 禁止在计算属性中直接修改data中的属性(可以调用方法书写逻辑)
"vue/return-in-computed-property": "error", // 强制在计算属性中存在return语句
"indent": ["error", 2],
"no-multiple-empty-lines": ["warn", { "max": 1 }]
}
}
复制代码
PS:我们自定义的规范可以使用发包的形式存在,项目中extends引用 尽可能避免开发人员操作
- Husky
// package.json
"husky":{
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
复制代码
- lint-staged
// package.json
"lint-staged": {
"*.{js,vue}": ["eslint"]
}
复制代码
PS:针对暂存区文件做校验 传送门
- commitlint
// package.json
"commitlint": {
"extends": ["@commitlint/config-conventional"]
}
复制代码
IDE
VScode 安装Eslint插件 并 配置编辑器 Settings.json 配置如下
// setting.json
// 在底部状态栏显示eslint
"eslint.alwaysShowStatus": true,
// 保存时
"editor.codeActionsOnSave": {
// eslint 自动修复
"source.fixAll.eslint": true
},
// 需要ESLint校验文件类型
"eslint.validate": [
"html", "javascript", "typescript", "vue"
]
复制代码
运行
-
暂存区Eslint校验
-
commit message校验
解决husky无效的情况
- 过程
首先会监测 .git/hooks/** 还是否存在对应 hook文件 (如:pre-commit、commit-msg ..)如果不存在则会创建hook文件,如果文件存在就检测是否包含 "#husky" 字样以确认是否由 husky 创建 如果检测文件存在并且不包含 "#husky" 就会跳过创建步骤,提示 "hook (existing user hook)"
- 解决
删除 .git/hooks 对应hook文件 重新安装 husky (注意删除的hook文件不包含其他自定义内容)
本文作者:自如大前端研发中心-刘子毅
招聘信息
自如大前端研发中心招募新同学!
FE/IOS/Android工程师看过来
公司福利有:
- 全额五险一金,并额外购买商业保险
- 免费健身房+年度体检
- 公司附近租房9折优惠
- 每年2次晋升机会 办公地点:北京酒仙桥普天实业科技园 欢迎对技术有执着热爱的你加入我们!简历请投递 zhangxl122@ziroom.com!