标准化编程规范eslint/prettier + husky + lint-staged + commitlint

193 阅读3分钟

eslint配置

  1. 安装eslint插件
  2. 配置.eslintrc.js文件
// ESLint 配置文件遵循commonJS的导出规则
module.exports = {
   // 表示当前目录即为根目录
  root: true,
  // env表示启用ESLint检测的环境
  env: {
    node: true
  },
  // ESLint中基础配置需要继承的配置
  extends: [
    'plugin:vue/vue3-essential',
    '@vue/standard'
  ],
  // 解析器
  parserOptions: {
    parser: '@babel/eslint-parser'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'quote-props': 'off',
    'quotes': 'warn'
  }
}

Prettier配置

  1. 安装prettier插件
  2. 在项目中新建.prettierrc文件
  3. 在该文件中写入如下配置
{
    // 不尾随分号
  "semi": false,
  // 单引号
  "singleQuote": true,
  // 多行逗号分割的语法中,最后一行不加单引号
  "trailingComma": "none"
}
  1. 打开vscode设置面板设置format on save

GIT提交规范

什么是Git Hooks

git在执行某个事件之前或之后进行一些其他额外的操作

常用钩子 commit-msg:可以用来规范标准格式,并且可以按需指定是否拒绝本次提交 pre-commit:会在提交之前被调用,并且可以按需指定是否拒绝本次提交 以上都可以用git commit --no-verify绕过

使用husky+commitlint提交

两个工具 commitlint:用于检查提交信息 husky:是git hooks工具 注意: npm需在7.x以上版本!!!

  1. 安装commitlint依赖:
npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4
  1. 创建commit.config.js
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > 
commitlint.config.js
  1. 打开commit.config.js增加配置项

注意:确认保存为UTF-8的编码格式!!!


/**
 *
    常用的type类别
      upd:更新某功能(不是 feat, 不是 fix)
      feat:新功能(feature)
      fix:修补bug
      docs:文档(documentation)
      style:格式(不影响代码运行的变动)
      refactor:重构(即不是新增功能,也不是修改bug的代码变动)
      test:增加测试
      chore:构建过程或辅助工具的变动
    例子:
      git commit -m 'feat: 增加 xxx 功能'
      git commit -m 'bug: 修复 xxx 功能'
 */
module.exports = {
  extends: ['@commitlint/config-conventional'],
  /*
          rule由name和配置数组组成,如:'name:[0, 'always', 72]',
          数组中第一位为level,可选0,1,2,0为disable,1为warning,2为error,
          第二位为应用与否,可选always|never,第三位该rule的值。具体配置例子如下:
        */
  rules: {
    'type-enum': [
      2,
      'always',
      ['upd', 'feat', 'fix', 'refactor', 'docs', 'chore', 'style', 'revert']
    ],
    'type-case': [0],
    'type-empty': [0],
    'scope-empty': [0],
    'scope-case': [0],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
    'header-max-length': [0, 'always', 72]
  }
}
  1. 安装husky依赖
npm install husky@7.0.1 --save-dev
  1. 启动hooks,生成.husky文件夹
npx husky install
  1. package.json中生成prepare指令
npm set-script prepare "husky install"
  1. 执行npm run prepare
  2. 执行成功

image.png

  1. 添加commitlinthookhusky中,并指令在commit-msghooks下执行
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
  1. 此时的目录结构,不符合规范的将无法提交

image.png

image.png

  1. 添加pre-commit检测钩子
npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src"
  1. 修改package.json配置 (lint-staged vue-cli已经帮忙安装了)
“lint-staged": {
    "src/**/*.{js,vue}": [
        "eslint --fix",
        "git add"
    ]
}
  1. 修改pre-commit钩子
npx lint-staged

本文为个人学习总结,如有帮助到大家,不胜荣幸