代码检测规范和git提交规范

摘要:之前开发的项目,代码检测和提交规范都是已经配置好的,最近自己新建的项目就记录下相关配置过程。

1. ESlint配置

        2013年6月创建开源项目,提供一个插件化的JavaScript代码检测工具,创建项目是生成的eslintrc.js文件;

//Eslint配置文件遵循commonJS的导出规则,所导出的的对象就是ESLint的配置对象

//官方文档:https://www.tkcnn.com/eslint/core-concepts.html

// Eslint配置文件遵循commonJS的导出规则,所导出的的对象就是ESLint通的配置对象
// 文档:https://eslint.bootcss.com/docs/user-guide/configuring
module.exports = {
  // 表示当前目录即为根目录,ESLint规则将被限制到该目录下
  root: true,
  // env表示启用ESLint检测的环境
  env: {
    // node环境下启动ESLint检测
    node: true
  },
  // ESLint中基础配置需要继承的配置;
  extends: [
    'plugin:vue/vue3-essential',
    '@vue/standard'
  ],
  // 解析器:表述需要解析的内容
  parserOptions: {
    parser: 'babel-eslint'
  },
  // rules中需要修改的启用规则(key表示启用的规则)及其各自的错误级别
  /**
   * 错误级别分为三中:
   * "off"或者0 - 关闭规则
   * "warn"或者1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
   * "error"或者2 - 开启规则,使用错误界别的错误:error(当被触发的时候,程序会退出)
   */
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'space-before-function-paren': 'off'   //关闭此规则
  }
}

2. Prettier配置

        Prettier是代码格式化工具,具有开箱即用、直接集成到vscode的特点。保存时,让代码直接符合ESLint,prettier配置步骤如下:

  • vscode安装prettier可以在配置prettierrc时获得一些提示;
  • 根目录新增prettierrc文件,配置的JSON内容如下:
{
  //semi:表示js语句结尾是否尾随分号;
  "semi": false,
  //singleQuote:表示是否用单引号代替所有双引号;
  "singleQuote": true,
  //trailingComma:表示多行语法中,是否需要再最后一行添加逗号,有all\es5\none三个值;
  "trailingComma": "none"
}

注:也可以使用这样的配置

module.exports = {
  eslintIntegration: true,
  printWidth: 160, // 指定代码长度,超出换行
  tabWidth: 2, // tab 键的宽度
  useTabs: false, // 不使用tab
  semi: true, // 结尾加上分号
  singleQuote: true, // 使用单引号
  quoteProps: 'as-needed', // 要求对象字面量属性是否使用引号包裹
  trailingComma: 'none', // 确保对象的最后一个属性后有逗号
  bracketSpacing: true, // 大括号有空格 { name: 'rose' }
  arrowParens: 'always', // 箭头函数,单个参数添加括号
  requirePragma: false, // 是否严格按照文件顶部的特殊注释格式化代码
  insertPragma: false, // 是否在格式化的文件顶部插入Pragma标记,以表明该文件被prettier格式化过了
  proseWrap: 'preserve', // 按照文件原样折行
  htmlWhitespaceSensitivity: 'ignore', // html文件的空格敏感度,控制空格是否影响布局
  endOfLine: 'auto' // 结尾是 \n \r \n\r auto
};
  • vscode的设置中找到save,勾选Format on save;

        综上实现保存后,自动格式化代码的目的。此外,还需要处理几处细节

  1. vscode→首选项→设置→搜Tab Size设置制表符为两个空格2
  2. 如果vscode安装了多个代码格式化工具,可以右键选中『使用...格式化文档』配置默认的格式化程序
  3. ESLint和prettier之间冲突:space-before-function-paren;在ESLInt的rules中配置关闭:
'space-before-function-paren': 'off'

3. Git提交规范

        Angular团队Conventional Commits specification约定式提交,规范链接(约定式提交)。提交说明的结构如下所示

[optional scope]: 
[optional body]
[optional footer(s)]
译文:
<类型>[可选 范围]: <描述>
[可选 正文]
[可选 脚注]

3.1 Commitizen

        使用Commitizen进行代码提交(git commit)时,commitizen会再提交时填写所必须提交的字段;

1.全局安装Commitizen(建议使用有管理员权限的终端)

sudo npm install -g [email protected]

2.安装配置cz-customizable插件

        1.使用npm下载cz-customizable

npm i [email protected] --save-dev

        2.添加下列配置再package.json中

...
"config": {
  "commitizen": {
    "path": "node_modules/cz-customizable"   //commitizen的自定义配置的安装位置
  }
}

3.根目录下创建.cz-config.js自定义提示文件

module.exports = {
  //可选类型
  types: [
    { value: 'feat', name: 'feat: 新功能' },
    { value: 'fix', name: 'fix: 修复' },
    { value: 'docs', name: 'docs: 文档变更' },
    { value: 'style', name: 'style: 代码格式(不影响代码运行的变动)' },
    { value: 'refactor', name: '重构(即不增加feature,也不修复bug)' },
    { value: 'perf', name: 'perf: 性能优化' },
    { value: 'test', name: 'test: 增加测试' },
    { value: 'chore', name: 'chore: 构建过程或辅助工具的变动' },
    { value: 'revert', name: 'revert: 回退' },
    { value: 'build', name: 'build: 打包' }
  ],
  //消息步骤
  messages: {
    type: '请选择提交的类型:',
    customScope: '请输入修改范围(可选)',
    subject: '请简要描述提交(必填)',
    body: '请输入详细描述(可选)',
    footer: '请输入要关闭的issue(可选)',
    confirmCommit: '确认要使用以上信息提交? (y/n)'
  },
  //跳过问题
  skipQuestions: ['body', 'footer'],
  //subject文字默认长度是72
  subjectLimit: 72
}

4. 使用git cz代替git commit。使用git cz代替git commit即可看到上述提示内容

czh12@czh12deiMac vue-admin % **git add .**
czh12@czh12deiMac vue-admin % **git cz**
[email protected], [email protected]

All lines except first will be wrapped after 100 characters.
? 请选择提交的类型: feat: 新功能
? 请输入修改范围(可选) git
? 请简要描述提交(必填) add commitizen
? 请输入详细描述(可选) 使用commitizen提交代码
? 请输入要关闭的issue(可选) 

###--------------------------------------------------------###
feat(git): add commitizen

使用commitizen提交代码
###--------------------------------------------------------###

? 确认要使用以上信息提交? (y/n) Yes
 > running pre-commit hook: lint-staged
  ↓ Stashing changes... [skipped]
    → No partially staged files found...
  ✔ Running tasks...
[master 5904db7] feat(git): add commitizen
 3 files changed, 512 insertions(+), 7 deletions(-)
 create mode 100644 .cz-config.js
chenzh12@chenzh12deiMac vue-admin % **git log**
commit 5904db74cd7128e4957dbcdcd45d33033cb4bdca (HEAD -> master)
Author: zhenghuachen 
Date:   Tue Oct 31 18:00:15 2023 +0800

    feat(git): add commitizen
    
    使用commitizen提交代码

3.2 Git Hooks

        上节完成了Commitizen提交的配置,但是需要使用git cz替换git commit才能实现,如果不使用git cz上述提交规范就没有预约效果。本节实现不符合约定式提交规范时,阻止当前提交,并抛出错误提示。

        本节实现的功能需要借助Git hooks,它是是一种在提交代码之前或之后执行特定操作的技术。本节主要借助一下两种钩子:

Git Hooks 调用时机 说明
pre-commit git commit执行前他不接受任何参数,并且在获取提交日志消息并进行提交之前被调用。脚本git commit以非零状态退出会导致命令在创建提交之前停止。 可以使用 git commit —no-verify绕过
commit-msg git commit执行前 、可以用于将消息规范为魔种项目标准格式。还可以用于在检查消息文件后拒绝提交 可以使用 git commit —no-verify绕过

简单来说:

commit-msg:可以用来贵干化标准格式,并且可以按需指定是否要拒绝本次提交;

pre-commit:会在提交前被调用,并且可以按需指定是否要拒绝本次提交。

使用git hooks校验提交信息需要使用到如下工具:

commitlint:用于检查提交信息(https://github.com/conventional-changelog/commitlint)

husky: 是git hooks工具(https://github.com/typicode/husky)

注: 需要保证npm版本是7.X以上

3.2.1 commitlint安装

1. 安装依赖

npm install --save-dev @commitlint/[email protected] @commitlint/[email protected]

2. 创建commitlint.config.js文件。可以直接执行下面代码

echo "module.exports = {extends: ['@commitlint/config-conventional]'}" >
commitlint.config.js

        也可以手动新建commitlint.config.js并输入,表示导出的对象继承了这个第三方的包

module.exports = {
  extends: ['@commitlint/config-conventional']
}

3. 打开commitlint.config.js, 增加配置项

module.exports = {
  // 继承的规则
  extends: ['@commitlint/config-conventional'],
  // 定义规则
  roles: {
    // type 的类型定义: 表示git提交的type必须再以下类型范围
    'type-enum': [
      // 当前验证的错误级别,2表示错误
      2,
      // 在什么情况下进行验证
      'always',
      // 泛型内容
      [
        'feat', // 'feat: 新功能'
        'fix', // 'fix: 修复'
        'docs', // 'docs: 文档变更'
        'style', // 'style: 代码格式(不影响代码运行的变动)'
        'refactor', // '重构(即不增加feature,也不修复bug)'
        'perf', // 'perf: 性能优化'
        'test', // 'test: 增加测试'
        'chore', // 'chore: 构建过程或辅助工具的变动'
        'revert', // 'revert: 回退'
        'build' // 'build: 打包'
      ]
    ],
    // subject 大小写不做校验
    'subject-case': [0]
  }
}
3.2.2 husky安装

1. 安装依赖:npx husky install

czh12@czh12deiMac vue-admin % npx husky install
husky - Git hooks installed

2. 启动hooks,生成.husky文件夹:npx husky install

czh12@czh12deiMac vue-admin % npx husky install
husky - Git hooks installed

3. 再package.json中生成prepare指令(需要npm>7.0)

        可以手动添加,也可以通过如下指令生成

npm set-script prepare "husky install"

代码检测规范和git提交规范_第1张图片

4. 执行prepare指令:npm run prepare

czh12@czh12deiMac vue-admin % npm run prepare

> [email protected] prepare
> husky install

husky - Git hooks installed

5. 添加commitlint的hooks到husky中,并指令在commit-msg的hooks下执行npx —no-install commitlint —edit "$1"指令

        通过husky监听git hooks,在git hooks的commit-msg的回调的hooks里面执行commitlint来完成对应的提交代码的检测

czh12@czh12deiMac vue-admin % npx husky add .husky/commit-msg 'npx --no-install
 commitlint --edit "$1"'
husky - created .husky/commit-msg

        此时的.husky文件结构

代码检测规范和git提交规范_第2张图片

        此时,不符合规范的提交将会被阻止

czh12@czh12deiMac vue-admin % git add .     
czh12@czh12deiMac vue-admin % git commit -m 'test'
⧗   input: test
✖   subject may not be empty [subject-empty]
✖   type may not be empty [type-empty]

✖   found 2 problems, 0 warnings
ⓘ   Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

husky - commit-msg hook exited with code 1 (error)

        综上,代码强制规范化提交要求以配置完成,不符合提交规范的代码将无法提交。

3.3 通过pre-commit检测提交时代码规范

        ESLint和Prettier解决了本地代码格式问题,那么如果本地没有配置,提交时如何规避这种问题?这就需要使用husky和ESLint配合才可以。通过husky检测pre-commit钩子,在该钩子执行npx eslint —ext .js,.vue src(src目录下检测.js和.vue的文件)指令进行相关代码格式化规范检测

1. 执行npx husky add .husky/pre-commit "npx eslint —ext .js,.vue src"添加commit时(npx eslint —ext .js,.vue src 会在执行到该hooks是运行)

2. 执行上述命令,会在.husky文件夹中生成pre-commit文件,其内容如下:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx eslint --ext .js,.vue src

3.4 通过lint-staged自动修复格式错误

        上节通过pre-commit处理了检测代码提交规范的问题,但是有两处需要优化。

        首先,若只修改个别文件,没必要检测所有文件的代码格式;

        其次,检测出错误依然需要手动修改。

        lint-staged可以让代码检查值作用域本次修改的代码,并自动修复并且推送。lint-staged的使用如下,修改package.json中lint-staged的配置为:

"lint-staged": {
  "src/**/* .(js,vue)": [
    "eslint --fix",
    "git add"
  ]
},

        如上配置,会在本地commit前校验提交代码是否符合ESLint规范,符合则提交,不符合则尝试修复,修复成功则提交,失败则提示。

        同时还要修改pre-commit中的内容,使其使用lint-staged检测提交

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged

        综上,git提交规范配置完成。总结一下:

        代码格式规范,通过ESLint+Prettier+VSCode配合进行了处理,达到了保存代码,自动格式化代码格式的目的。git提交规范使用了husky来检测Git hooks钩子,并通过以下插件完成配置:

约定式提交规范

commitizen:git提交规范化工具

commitlint:用于检测提交信息

pre-commit: git hooks 钩子

lint-staged:只检测本次修改更新后的代码,并将出现的错误自动修复并推送。

你可能感兴趣的:(开发工具,git,vscode,前端)