Vue3+Ts+Vite项目(第三篇)——配置husky、stylelint、commitlint,配置git提交代码校验


简介

做什么:本文将从零开始带你配置huskystylelint,完成代码提交git前的强制校验,保证代码风格和一致性
技术栈:Vue3 + TypeScript + Vite


一、项目环境

1.1 node.js v16.0.0 及以上 (我 v16.14.1)

// 查看node 版本 : 打开小黑窗输入 node -v
node -v

1.2 pnpm v8.0.0 及以上(我 v8.6.6)

// 查看pnpm 版本 : 打开小黑窗输入 pnpm -v
pnpm -v

二、创建项目

2.1 安装 pnpm

npm i pnpm -g

2.2 创建项目-不多赘述

pnpm create vite '项目名称'

三、配置 eslint

3.1 安装 eslint

pnpm i eslint -D

3.2 生成eslint配置文件

pnpm eslint --init

运行命令后会在根目录生成一个.eslintrc.cjs文件,其中的代码如下:

module.exports = {
    
    
    "env": {
    
    
        "browser": true,
        "es2021": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:vue/vue3-essential",
        'plugin:prettier/recommended',
    ],
    "overrides": [
        {
    
    
            "env": {
    
    
                "node": true
            },
            "files": [
                ".eslintrc.{js,cjs}"
            ],
            "parserOptions": {
    
    
                "sourceType": "script"
            }
        }
    ],
    "parserOptions": {
    
    
        "ecmaVersion": "latest",
        "parser": "@typescript-eslint/parser",
        "sourceType": "module"
    },
    "plugins": [
        "@typescript-eslint",
        "vue"
    ],
  "rules": {
    
    }
}

3.3 完善 .eslintrc.cjs 文件中的 rules 对象

  rules: {
    
    
    // eslint(https://eslint.bootcss.com/docs/rules/)
    'no-var': 'error', // 要求使用 let 或 const 而不是 var
    'no-multiple-empty-lines': ['warn', {
    
     max: 1 }], // 不允许多个空行
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-unexpected-multiline': 'error', // 禁止空余的多行
    'no-useless-escape': 'off', // 禁止不必要的转义字符

    // typeScript (https://typescript-eslint.io/rules)
    '@typescript-eslint/no-unused-vars': 'error', // 禁止定义未使用的变量
    '@typescript-eslint/prefer-ts-expect-error': 'error', // 禁止使用 @ts-ignore
    '@typescript-eslint/no-explicit-any': 'off', // 禁止使用 any 类型
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/no-namespace': 'off', // 禁止使用自定义 TypeScript 模块和命名空间。
    '@typescript-eslint/semi': 'off',

    // eslint-plugin-vue (https://eslint.vuejs.org/rules/)
    'vue/multi-word-component-names': 'off', // 要求组件名称始终为 “-” 链接的单词
    'vue/script-setup-uses-vars': 'error', // 防止<script setup>使用的变量<template>被标记为未使用
    'vue/no-mutating-props': 'off', // 不允许组件 prop的改变
    'vue/attribute-hyphenation': 'off' // 对模板中的自定义组件强制执行属性命名样式
  }

3.4 新建忽略文件

在项目根目录新建 .eslintignore 文件,并写入如下代码:

dist
node_modules

3.5 添加脚本

packjson.jsonscript 字段中添加俩行命令

"lint": "eslint src",
"fix": "eslint src --fix"

3.6 检测是否生效

main.ts 中使用 var 数据类型,终端运行 pnpm run lint 命令,出现如下错误说明 eslint 安装并配置成功
在这里插入图片描述
接着试运行修复命令 pnpm run fix,修复成功,证明配置成功
在这里插入图片描述


四、配置 prettier

在我们的项目中,eslint 应主要负责校验语法校验,prettier 应主要负责代码格式化

4.1 安装 prettier

pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier

4.2 运行 pnpm run lint

装包完成之后在终端运行 pnpm run lint 命令,查看本次装包是否影响项目

pnpm run lint

如果你运行 pnpm run lint 命令后报类似这样的错:

Oops! Something went wrong! :(

ESLint: 8.44.0

TypeError: prettier.resolveConfig.sync is not a function
Occurred while linting D:\Users\Desktop\study_wy\src\main.ts:1
Rule: “prettier/prettier”
at Program (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected][email protected][email protected][email protected]\node_modules\eslint-plugin-prettier\eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\linter.js:1050:28)
at D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\safe-emitter.js:45:58
at Array.forEach (<anonymous>)
at Object.emit (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\node-event-generator.js:340:14) at CodePathAnalyzer.enterNode (D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\code-path-analysis\code-path-analyzer.js:795:23)
at D:\Users\Desktop\study_wy\node_modules.pnpm\[email protected]\node_modules\eslint\lib\linter\linter.js:1085:32

如若报上面这样类似的错,则运行下面这条命令,不报错则进入下一步:

pnpm install prettier@^2.4.0 -D

在这里插入图片描述

4.3 新建 prettier 配置文件

根目录下新建 .prettierrc.json 文件,并填入如下代码:

{
    
    
	"printWidth": 100,
	"tabWidth": 2,
	"useTabs": true,
	"semi": false,
	"singleQuote": true,
	"trailingComma": "none",
	"bracketSpacing": true,
	"bracketSameLine": true,
	"arrowParens": "always",
	"htmlWhitespaceSensitivity": "ignore",
	"vueIndentScriptAndStyle": false,
	"endOfLine": "auto",
	"singleAttributePerLine": false
}

各文件说明:

{
    
    
  "printWidth": 100,	//每行最多显示的字符数
  "tabWidth": 2,//tab的宽度 2个字符
  "useTabs": true,//使用tab代替空格
  "semi": false,//结尾使用分号
  "singleQuote": true,//使用单引号代替双引号
  "trailingComma": "none",//结尾是否添加逗号
  "bracketSpacing": true,//对象括号俩边是否用空格隔开
  "bracketSameLine": true,;//组件最后的尖括号不另起一行
  "arrowParens": "always",//箭头函数参数始终添加括号
  "htmlWhitespaceSensitivity": "ignore",//html存在空格是不敏感的
  "vueIndentScriptAndStyle": false,//vue 的script和style的内容是否缩进
  "endOfLine": "auto",//行结尾形式 mac和linux是\n  windows是\r\n 
  "singleAttributePerLine": false //组件或者标签的属性是否控制一行只显示一个属性
}

4.4 新建忽略文件

根目录下新建 .prettierignore 文件并填入如下代码:

/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*

4.5 完善 .eslintrc.cjs 文件

'plugin:prettier/recommended',

在这里插入图片描述
main.ts 中加入一句测试用的 console,然后运行 pnpm run lint,可以看到控制台给出了提示
在这里插入图片描述

4.6 添加脚本

packjson.json 文件的script 字段中添加一行命令

 "format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" "

运行 pnpm run format 可以看到将所有允许的文件都格式化了一遍
在这里插入图片描述


五、配置stylelint

stylelint 是 css 的格式化工具。可格式化css代码、检查css语法错误与不合理的写法,指定css书写顺序等

5.1 安装 stylelint

本项目中使用scss作为预处理器,安装以下依赖:

pnpm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss -D

5.2 装包完成后

5.1 命令执行完成后,如若报类似下面的警告,可以先不管,接着看步骤5.2

└─┬ stylelint-config-prettier 9.0.5
└── ✕ unmet peer stylelint@“>= 11.x < 15”: found 15.10.1

5.3 新建 stylelint 配置文件

在项目根目录下新建 .stylelintrc.cjs,并填入如下代码:

module.exports = {
    
    
  extends: [
    'stylelint-config-standard', // 配置stylelint拓展插件
    'stylelint-config-html/vue', // 配置 vue 中 template 样式格式化
    'stylelint-config-standard-scss', // 配置stylelint scss插件
    'stylelint-config-recommended-vue/scss', // 配置 vue 中 scss 样式格式化
    'stylelint-config-recess-order', // 配置stylelint css属性书写顺序插件,
    'stylelint-config-prettier', // 配置stylelint和prettier兼容
  ],
  overrides: [
    {
    
    
      files: ['**/*.(scss|css|vue|html)'],
      customSyntax: 'postcss-scss',
    },
    {
    
    
      files: ['**/*.(html|vue)'],
      customSyntax: 'postcss-html',
    },
  ],
  ignoreFiles: [
    '**/*.js',
    '**/*.jsx',
    '**/*.tsx',
    '**/*.ts',
    '**/*.json',
    '**/*.md',
    '**/*.yaml',
  ],
  /**
   * null  => 关闭该规则
   * always => 必须
   */
  rules: {
    
    
    'value-keyword-case': null, // 在 css 中使用 v-bind,不报错
    'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
    'function-url-quotes': 'always', // 要求或禁止 URL 的引号 "always(必须加上引号)"|"never(没有引号)"
    'no-empty-source': null, // 关闭禁止空源码
    'selector-class-pattern': null, // 关闭强制选择器类名的格式
    'property-no-unknown': null, // 禁止未知的属性(true 为不允许)
    'block-opening-brace-space-before': 'always', //大括号之前必须有一个空格或不能有空白符
    'value-no-vendor-prefix': null, // 关闭 属性值前缀 --webkit-box
    'property-no-vendor-prefix': null, // 关闭 属性前缀 -webkit-mask
    'selector-pseudo-class-no-unknown': [
      // 不允许未知的选择器
      true,
      {
    
    
        ignorePseudoClasses: ['global', 'v-deep', 'deep'], // 忽略属性,修改element默认样式的时候能使用到
      },
    ],
  },
}

5.4 新建 stylelint 忽略文件

在项目根目录下新建 .stylelintignore 文件,并填入如下代码:

/node_modules/*
/dist/*
/html/*
/public/*

5.5 添加脚本

packjson.json 文件的 script 字段中添加命令

"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"

六、配置 husky

6.1 安装 husky

pnpm install -D husky

6.2 生成 husky 配置文件

注:执行此命令前,要先 git init 或者是先将本项目链接到远程仓库(github、gitee等)

npx husky-init

执行此命令后会在根目录下生成个一个.husky目录,在这个目录下面会有一个pre-commit文件,内容如下。这个文件里面的命令在我们执行commit的时候就会执行

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm format

七、配置 commitlint

配置 git 提交时的 commit 信息,统一提交 git 提交规范

7.1 安装 commitlint

pnpm add @commitlint/config-conventional @commitlint/cli -D

7.2 新建 commitlint 配置文件

在项目根目录下新建 commitlint.config.cjs 文件,并填入如下代码:

module.exports = {
    
    
  extends: ['@commitlint/config-conventional'],
  // 校验规则
  rules: {
    
    
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'docs',
        'style',
        'refactor',
        'perf',
        'test',
        'chore',
        'revert',
        'build',
      ],
    ],
    '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],
  },
}

配置说明:

'feat',     //新特性、新功能
'fix',      //修改bug
'docs',     //文档修改
'style',    //代码格式修改, 注意不是 css 修改
'refactor', //代码重构
'perf',     //优化相关,比如提升性能、体验
'test',     //测试用例修改
'chore',    //其他修改, 比如改变构建流程、或者增加依赖库、工具等
'revert',   //回滚到上一个版本
'build',    //编译相关的修改,例如发布版本、对项目构建或者依赖的改动

7.3 添加脚本

packjson.json 文件的 script 字段中添加命令

 "commitlint": "commitlint --config commitlint.config.cjs -e -V"

7.4 搭配 husky 来使用

npx husky add .husky/commit-msg 

在根目录下 husky文件夹中的 commit-msg中添加如下命令

#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm commitlint

7.5 提交规范

提交示范:git commit -m 'feat: 新增商品页查询功能’
此处并非只能用 feat 作为前缀,还能使用其他前缀,详情见 步骤7.2

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_61402485/article/details/131612959