前端团队规范探索 – 提交代码规范校验

这是我参与更文挑战的25天,活动详情查看 更文挑战

husky 一个git钩子插件

husky经常配合lint-staged一起使用,在git提交的钩子中用lint-staged做一些操作,例如让你提交前运行vue自带的代码格式化工具:vue-cli-service lint,或者运行prettier –write,它的作用是可以配置一些规则,且只对本次提交的各种文件进行检查而不是整个项目。

但是我们已经做到了自动保存格式化,这种方式明显是多余的,所以我们现在只需要一个husky,来对commit提交做些规范工作。

安装

yarn add husky -D
复制代码

新版使用方法:
package.json中添加脚本

"scripts": {
    "prepare": "husky install",
  }
复制代码

执行初始化

npm run prepare
复制代码

会在根目录生成一个目录,使用命令往git钩子中添加要执行的命令:

npx husky add .husky/pre-commit "npm test"
复制代码

git commit时对应的生命周期会触发对应的命令。

如果你想使用旧版的配置,需要指定版本安装:

yarn add husky@3.0.9 -D
复制代码

package.json配置

"husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 
      "pre-commit": "xxx" // pre-commit,提交前的钩子
    }
  },
复制代码

Commitize 统一代码提交信息

安装:

yarn add commitizen cz-conventional-changelog @commitlint/cli @commitlint/config-conventional -D
复制代码

package.json添加如下配置

  "config": {
    "commitizen": {
      "path": "node_modules/cz-conventional-changelog"
    }
  },
   "commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ]
  },
复制代码

在根目录创建 commitlint.config.js 配置我们的commit规则

/**
 * feat 新功能
 * fix 修补bug
 * docs 文档修改
 * style 样式修改
 * build 代码编译
 * refactor 代码重构
 * code 代码优化
 * test 测试用例
 */
module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'build', 'refactor', 'test', 'code']],
  },
}
复制代码

附录:config-conventional

最终不符合规范的git commit将会被拦截。

package.json添加

"scripts": {
    "c": "git add . && git-cz"
  }
复制代码

提交代码使用 yarn cnpm run c,即可使用命令行工具以Angular规范(社区使用最广泛的规范)进行代码提交。

终端工具选择:

mac:无所谓 ,自带终端就很强大。

windows:我遇到过还有在使用CMD的同事,曾经也用过一段时间装git附赠的gitBash工具,这些都不太好用,建议使用vsCode自带的Terminal工具就很好。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享