前端实用工具(二):编程规范化解决方案

目录

本地代码规范化工具

代码检测工具ESLint

代码格式化工具Prettier

远程代码规范化工具

远程提交规范化工具commitizen

提交规范检验工具commitlint +husky

什么是git hooks

commitlint安装

husky安装

检测代码提交规范 ESLint +husky

自动修复格式错误lint-staged


本地代码规范化工具

代码检测工具ESLint

最新的ESLint9,配置文件和配置规则有很大的区别  中文文档

配置规则和忽闻文件都整合到了eslint.config.js

import globals from "globals";
import pluginJs from "@eslint/js";
import pluginVue from "eslint-plugin-vue";


/** @type {import('eslint').Linter.Config[]} */
export default [
  {files: ["**/*.{js,mjs,cjs,vue}"]},
  {languageOptions: { globals: globals.browser }},
  // JavaScript 默认推荐规则
  pluginJs.configs.recommended,
  // Vue 默认推荐规则
  ...pluginVue.configs["flat/essential"],
  {
    rules: {
       // 强制使用分号
      'semi': ['error', 'always'],
      
      // 强制使用单引号
      'quotes': ['error', 'single'],
      
      // 缩进配置
      'indent': ['error', 2],
      
      // 对象属性换行配置
      'object-property-newline': ['error', {
        allowMultiplePropertiesPerLine: true
      }],
      
      // 组件名称格式
      'vue/multi-word-component-names': 'off',
      
      // 禁止在模板中使用 this
      'vue/this-in-template': ['error', 'never'],
      
      // Props 命名规范
      'vue/prop-name-casing': ['error', 'camelCase'],
      
      // 强制 Props 类型定义
      'vue/require-prop-types': 'error',
      
      // 关闭一些烦人的规则
      'no-unused-vars': 'off',
      'no-console': 'off',
      'vue/no-unused-components': 'warn'
    }
  },
  {
    ignores: [  // 构建输出目录
      "dist/**",
      "build/**",
      
      // 配置文件
      "*.config.js",
      "*.config.ts",
      ".eslintrc.*",
      
      // 依赖目录
      "node_modules/**",
      
      // 静态资源目录
      "public/**",
      "src/assets/**",
      
      // 自动生成的文件
      "auto-imports.d.ts",
      "components.d.ts",
      
      // 测试覆盖率报告
      "coverage/**",
      
      // 环境配置文件
      ".env.*",
      
      // 其他常见的不需要检查的文件
      "*.min.js",
      "*.lock"
    ]
  }
];

如果ESLint不生效:

VSCodo清除ESLint缓存

  1. 按 Ctrl + Shift + P 打开命令面板
  2. 输入并选择 ESLint: Restart ESLint Server
  3. 或者直接重启 VS Code

eslint以下版本:

项目中的.eslintrc.js 文件

// 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"
  },
  // 需要修改的启用规则及其各自的错误级别
  /**
   * 错误级别分为三种:
   * "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"
  }
};

之后ESLint规则在rules中以键值对的形式添加

    代码格式化工具Prettier

    npm install -D prettier eslint-config-prettier eslint-plugin-prettier

    eslint-config-prettier:禁用可能冲突的 ESLint 规则,禁用所有与 Prettier 格式化可能冲突的 ESLint 规则(遇到冲突才需要,可选)

    eslint-plugin-prettier: 将 Prettier 规则集成到 ESLint 中,让 ESLint 能够运行 Prettier 规则,使得代码格式检查和修复可以和其他 ESLint 规则一起工作

    工作流程:

    • ESLint 检查代码规范
    • Prettier 通过 eslint-plugin-prettier 格式化代码
    • eslint-config-prettier 确保没有规则冲突

    新建 .prettierrc 文件,该文件为 perttier 默认配置文件

    {
      "singleQuote": true,
      "semi": true,
      "tabWidth": 2,
      "quoteProps": "as-needed",
      "trailingComma": "none",
      "bracketSpacing": true,
      "arrowParens": "always",
      "rangeStart": 0,
      "requirePragma": false,
      "insertPragma": false,
      "proseWrap": "preserve",
      "endOfLine": "lf"
    }

    在VSCode设置中,搜索 save ,勾选 Format On Save

    ESLint和prettier的常见问题?

    ● VSCode默认制表符是4个空格,而ESLint希望一个制表符是两个空格

    ● 如果VSCode安装多个代码格式化工具可能会冲突

    ● ESLint和Prettier之间有冲突,默认ESLint括号前会有空格需要手动关闭'space-before-function-paren':'off'

    远程代码规范化工具

    远程提交规范化工具commitizen

    commitizen 仓库名为 cz-cli ,它提供了一个 git cz 的指令用于代替 git commit,简单一句话介绍它:

    当你使用 commitizen 进行代码提交(git commit)时,commitizen 会提交你在提交时填写所有必需的提交字段!

    commitizen安装步骤如下:

    1. 全局安装Commitizen
    npm install -g commitizen@4.2.4
    1. 安装并配置 cz-customizable 插件
    • 使用 npm 下载 cz-customizable
    npm i cz-customizable@6.3.0 --save-dev
    • 添加以下配置到 package.json
    ...
      "config": {
        "commitizen": {
          "path": "node_modules/cz-customizable"
        }
      }
    1. 项目根目录下创建 .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
    }
    1. 使用 git cz 代替 git commit

    补充:

    不同的团队可能会有不同的标准,那么咱们今天就以目前使用较多的 Angular团队规范 延伸出的 Conventional Commits specification(约定式提交) 为例,来为大家详解 git 提交规范

    约定式提交规范要求如下:

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

    其中 <type> 类型,必须是一个可选的值,比如:

    1. 新功能:feat
    2. 修复:fix
    3. 文档变更:docs
    4. ....

    如果忘记了git cz指令,我们有没有方法限制这种错误的出现?

    我们可以使用git hooks + commitlint阻止不规范提交

    提交规范检验工具commitlint +husky

    检查提交描述是否符合规范要求husky+commitlint

    什么是git hooks

    Git hooks(git 钩子 || git 回调方法):git在执行某些事件之间或之后进行一些其他额外的操作

    PS:详细的 HOOKS介绍 可点击这里查看

    整体的 hooks 非常多,当时我们其中用的比较多的其实只有两个:

    1. commit-msg:可以用来规范化标准格式,并且可以按需指定是否要拒绝本次提交
    2. pre-commit:会在提交前被调用,并且可以按需指定是否要拒绝本次提交

    • Husky:主要作用是简化git hooks的配置和管理,可以通过配置文件定义钩子行为(简化拆分git hooks)
    • commitlint:用来检查提交信息

    Husky 和 commitlint 通常一起使用,Husky监听commit-msg函数,在每次提交之前触发commitlint 检查提交规范

    下面我们分别安装两个工具

    commitlint安装

    1. 安装依赖:
    npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4
    1. 创建 commitlint.config.js 文件(也可以手动创建)
    echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
    1. 打开 commitlint.config.js , 增加配置项( config-conventional 默认配置点击可查看 ):
    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]
      }
    }

    注意:确保保存为 UTF-8 的编码格式,否则可能会出现以下错误:

    husky安装

    1. 安装依赖:
    npm install husky@7.0.1 --save-dev
    1. 启动 hooks , 生成 .husky 文件夹
    npx husky install

    1. package.json 中生成 prepare 指令( 需要 npm > 7.0 版本

    命令无效就手动添加

    npm set-script prepare "husky install"

    1. 执行 prepare 指令
    npm run prepare
    1. 执行成功,提示

    1. 添加 commitlinthookhusky中,并指令在 commit-msghooks 下执行 npx --no-install commitlint --edit "$1" 指令
    npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
    1. 此时的 .husky 的文件结构

    至此, 不符合规范的 commit 将不再可提交:

    PS F:\xxxxxxxxxxxxxxxxxxxxx\test-admin> git commit -m "测试"
    ⧗   input: 测试
    ✖   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)

    检测代码提交规范 ESLint +husky

    在前面的ESLint和Prettier配合解决的是本地代码的格式问题,而且我们需要手动在VSCode中配置自动保存

    如果本地忘记配置了,怎么在提交之前如何检测代码格式是否错误?

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

    执行脚本,在pre-commit 中执行检测代码

    npx husky add .husky/pre-commit "npx eslint --ext .js,.vue src"

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

    此时如果不符合ESLint标准,代码提交失败

    自动修复格式错误lint-staged

    lint-staged 可以让你当前的代码检查 只检查本次修改更新的代码,并在出现错误的时候,自动修复并且推送

    1. 修改 package.json 配置
    "lint-staged": {
        "src/**/*.{js,vue}": [
          "eslint --fix",
          "git add"
        ]
      }
    1. 如上配置,每次它只会在你本地 commit 之前,校验你提交的内容是否符合你本地配置的 eslint规则(这个见文档 ESLint ),校验会出现两种结果:
    • 如果符合规则:则会提交成功。
    • 如果不符合规则:它会自动执行 eslint --fix 尝试帮你自动修复,如果修复成功则会帮你把修复好的代码提交,如果失败,则会提示你错误,让你修好这个错误之后才能允许你提交代码。
    1. 修改 .husky/pre-commit 文件
    #!/bin/sh
    . "$(dirname "$0")/_/husky.sh"
    
    npx lint-staged
    1. 再次执行提交代码
    2. 发现 暂存区中 不符合 ESlint 的内容,被自动修复

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值