对于代码监测流目前大多数分为两种,服务端校验和本地提交校验,这里简单阐述下优缺点 服务端校验通过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": {
"Swiper": "readonly",
"ZIROOMCommon": "readonly",
"$": "readonly"
"rules": {
"no-mixed-spaces-and-tabs": "off",
"no-dupe-keys": "error",
"no-undef": "error",
"no-empty": "error",
"no-unused-vars": "warn",
"no-console": "warn",
"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",
"vue/no-use-v-if-with-v-for": [
"error",
"allowUsingIterationVar": true
],
"vue/no-unused-components": "warn",
"vue/require-valid-default-prop": "error",
"vue/valid-v-for": "error",
"vue/no-side-effects-in-computed-properties": "error",
"vue/return-in-computed-property": "error",
"indent": ["error", 2],
"no-multiple-empty-lines": ["warn", { "max": 1 }]
PS:我们自定义的规范可以使用发包的形式存在,项目中extends引用 尽可能避免开发人员操作
Husky
"husky":{
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
lint-staged
"lint-staged": {
"*.{js,vue}": ["eslint"]
PS:针对暂存区文件做校验
commitlint
"commitlint": {
"extends": ["@commitlint/config-conventional"]
VScode 安装Eslint插件 并 配置编辑器 Settings.json 配置如下
"eslint.alwaysShowStatus": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
"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次晋升机会
办公地点:北京酒仙桥普天实业科技园
欢迎对技术有执着热爱的你加入我们!简历请投递 [email protected]!