关于代码规范和git提交规范

115 阅读2分钟

代码

安装 vscode插件 Prettier - Code formatter

image.png

使用方法 1.vscode设置中搜索save Format On Save

image.png

2.设置空格占位符为2

image.png

3.在根目录创建.prettierrc 文件

image.png -进行配置 { "semi":false, //是否在最后添加; "singleQuote":true,//是否使用单引号 "trailingComma":"none"//是否添加对应的, }

git

全局安装 npm i -g commitizen@4.2.4 项目安装 npm i cz-customizable@6.3.0 --save-dev 在package.json 中添加

"config": { "commitizen": { "path": "node_modules/cz-customizable" } }

在根目录创建.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: 'refactor: 重构(既不是增加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/e/h)'
  },
  // 跳过问题
  skipQuestions: ['body', 'footer'],
  // subject文字长度默认是72
  subjectLimit: 72
}

然后我们使用git cz 代替git commit 提交

commitlint 配置

安装 npm install @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4 在根目录下创建 commitlint.config.js

module.exports = {
  // 继承的规则
  extends: ['@commitlint/config-conventional'],
  // 定义规则类型
  rules: {
    // type 类型定义,表示 git 提交的 type 必须在以下类型范围内
    'type-enum': [
      2,
      'always',
      [
        'feat', // 新功能 feature
        'fix', // 修复 bug
        'docs', // 文档注释
        'style', // 代码格式(不影响代码运行的变动)
        'refactor', // 重构(既不增加新功能,也不是修复bug)
        'perf', // 性能优化
        'test', // 增加测试
        'chore', // 构建过程或辅助工具的变动
        'revert', // 回退
        'build' // 打包
      ]
    ],
    // subject 大小写不做校验
    'subject-case': [0]
  }
}

接下来安装 npm install husky@7.0.1 --save-dev 对commitlint规则进行校验 然后执行 npx husky install 进行启动 执行完之后会出现一个.husky的文件夹

image.png

然后执行 npm set-script prepare 'husky install'生成快捷执行

image.png 执行 npm run prepare 如下图表示成功

image.png 执行 npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

image.png 检查一下,如下图配置成功

image.png

设置husky 监听pre-connit的钩子 npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src"

设置代码按照eslint自动修复

在package.json中进行配置

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

修改.husky 中pre-commit npx lint-staged 当提交遇到问题时会执行自动修复 image.png