9.标准化大厂编程规范解决方案之ESLint + Git Hooks

377 阅读5分钟

1.  Prettier 自动格式化插件处理

  • 安装Prettier - Code formatter
  • 打开vscode---设置---搜索save
  • 搜索Default Formatter,设置安装的插件
  • 在对应的代码目录结构下增加.prettierrc
{

  "semi": true,

  "singleQuote": false,

  "trailingComma": "none"

}
  • 自动保存时,就会按照规则自动格式化文件

参考

{

  "printWidth": 100, // 指定一行的最大宽度,超出此长度会换行

  "tabWidth": 2, // 指定缩进的空格数(如 Tab 键替换为空格的数量)

  "useTabs": false, // 是否使用 Tab 键代替空格,默认关闭

  "semi": true, // 是否在语句末尾添加分号

  "singleQuote": true, // 是否优先使用单引号 `'` 而不是双引号 `"`

  "trailingComma": "es5", // 控制逗号风格,例如多行对象或数组时是否显示尾随逗号。可选值:"none"(不加尾随逗号)、"es5"(ES5 允许的情况加尾随逗号,如对象、数组等)、"all"(所有情况都加尾随逗号)

  "bracketSpacing": true, // 是否在对象字面量 `{}` 内部保留空格

  "jsxBracketSameLine": false, // JSX 的闭合标签是否与内容放在同一行

  "arrowParens": "always", // 箭头函数参数只有一个时是否需要括号。可选值:"avoid"(可省略时就省略)、"always"(总是添加括号)

  "htmlWhitespaceSensitivity": "ignore", // 指定 HTML 文件中空格敏感度的配置选项。可选值:"css"(遵循 CSS 的显示属性)、"strict"(空格被认为是敏感的)、"ignore"(空格被认为是无关紧要的)

  "vueIndentScriptAndStyle": false, // 是否缩进 Vue 文件中的 `<script>` 和 `<style>` 标签

  "endOfLine": "auto", // 指定换行符的风格。可选值:"auto"(自动检测)、"lf"(\n)、"crlf"(\r\n)、"cr"(\r)

  "quoteProps": "as-needed", // 对象属性是否使用引号。可选值:"as-needed"(仅在需要时添加引号)、"consistent"(如果至少有一个属性需要引号,则所有属性都使用引号)、"preserve"(保留对象属性的引号)

  "proseWrap": "preserve" // 是否保留 markdown 文件中的换行符。可选值:"preserve"(保留换行符)、"always"(总是换行)、"never"(从不换行)

}

image.png

image.png

2.Commitizen助你规范化提交代码

  1. 全局安装Commitizen

    npm install -g commitizen@4.2.4
    
  2. 安装并配置 cz-customizable 插件

    1. 使用 npm 下载 cz-customizable

      npm i cz-customizable@6.3.0 --save-dev
      
    2. 添加以下配置到 package.json

      ...
        "config": {
          "commitizen": {
            "path": "node_modules/cz-customizable"
          }
        }
      
  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: '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
    }
    
  4. 使用 git cz 代替 git commit 使用 git cz 代替 git commit,即可看到提示内容

    3.什么是 Git Hooks

    1. 安装依赖:
    npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4
    
  5. 创建 commitlint.config.js 文件

    echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
    
  6. 打开 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]
      }
    }
    
    

1.husky

  1. 安装依赖:

    npm install husky@7.0.1 --save-dev
    
  2. 启动 hooks , 生成 .husky 文件夹

    npx husky install
    
  3. package.json 中生成 prepare 指令( 需要 npm > 7.0 版本

    npm set-script prepare "husky install"
    
  4. 执行 prepare 指令

    npm run prepare
    
  5. 执行成功

  6. 添加 commitlinthookhusky中,并指令在 commit-msghooks 下执行 npx --no-install commitlint --edit "$1" 指令

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

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

我们期望通过 husky 监测 pre-commit 钩子,在该钩子下执行 npx eslint --ext .js,.vue src 指令来去进行相关检测:

  1. 执行 npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src" 添加 commit 时的 hooknpx eslint --ext .js,.vue src 会在执行到该 hook 时运行)

  2. 该操作会生成对应文件 pre-commit

  3. 关闭 VSCode 的自动保存操作

  4. 修改一处代码,使其不符合 ESLint 校验规则

3.lint-staged 自动修复格式错误

  1. 修改 package.json 配置

    "lint-staged": {
        "src/**/*.{js,vue}": [
          "eslint --fix",
          "git add"
        ]
      }
    
  2. 如上配置,每次它只会在你本地 commit 之前,校验你提交的内容是否符合你本地配置的 eslint规则(这个见文档 ESLint ),校验会出现两种结果:

    1. 如果符合规则:则会提交成功。
    2. 如果不符合规则:它会自动执行 eslint --fix 尝试帮你自动修复,如果修复成功则会帮你把修复好的代码提交,如果失败,则会提示你错误,让你修好这个错误之后才能允许你提交代码。
  3. 修改 .husky/pre-commit 文件

    #!/bin/sh
    . "$(dirname "$0")/_/husky.sh"
    
    npx lint-staged
    
    
  4. 再次执行提交代码

  5. 发现 暂存区中 不符合 ESlint 的内容,被自动修复

4.如果是vite配置,子项目设置

1.增加.lintstagedrc.cjs文件

module.exports = {
  // '*.{vue,js,jsx,ts,tsx,cjs,mjs}': 'eslint --ignore-path .gitignore'
  "*.{vue,js,jsx,ts,tsx,cjs,mjs}": ["prettier --write", "eslint --fix --ignore-path .gitignore"],
  "*.json": "prettier --write",
  "*.md": "prettier --write"
};

5.配置vscode,实现保存时,自动通过premitter格式化

//.vscode/settings.json
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
  "eslint.run": "onSave",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "prettier.requireConfig": true,
  "prettier.useEditorConfig": false
}