Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验

这篇具有很好参考价值的文章主要介绍了Vue3+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 安装并配置成功
Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git
接着试运行修复命令 pnpm run fix,修复成功,证明配置成功
Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git


四、配置 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\registry.npmmirror.com+eslint-plugin-prettier@4.2.1_eslint-config-prettier@8.8.0_eslint@8.44.0_prettier@3.0.0\node_modules\eslint-plugin-prettier\eslint-plugin-prettier.js:138:40)
at ruleErrorHandler (D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\linter.js:1050:28)
at D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\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\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\node-event-generator.js:340:14) at CodePathAnalyzer.enterNode (D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\code-path-analysis\code-path-analyzer.js:795:23)
at D:\Users\Desktop\study_wy\node_modules.pnpm\registry.npmmirror.com+eslint@8.44.0\node_modules\eslint\lib\linter\linter.js:1085:32

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

pnpm install prettier@^2.4.0 -D

Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git

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',

Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git
main.ts 中加入一句测试用的 console,然后运行 pnpm run lint,可以看到控制台给出了提示
Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git

4.6 添加脚本

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

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

运行 pnpm run format 可以看到将所有允许的文件都格式化了一遍
Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git


五、配置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

Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验,Vue.js,Vite,Git,vue.js,javascript,git文章来源地址https://www.toymoban.com/news/detail-535638.html

到了这里,关于Vue3+Vite项目配置husky、stylelint、commitlint,实现git提交前代码校验的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • vite 创建vue3项目,使用 Prettier 统一格式化代码,集成 ESLint、Stylelint 代码校验规范

    在团队开发中,保持代码风格的一致性和代码质量的高度,对于项目的可维护性和可读性非常重要。为了实现这一目标,我们可以使用工具来自动格式化代码并进行代码校验,在开发过程中捕获潜在的问题,并提供修复建议。 本示例中,我们将使用 Vite 来创建一个新的 Vue

    2024年04月28日
    浏览(55)
  • vite+vue3+ts+eslint+prettier+husky+lint-stated 项目搭建

    项目搭建 创建初始项目 Node.js 版本 14.18+,16+ npm create vite@latest my-vue-app --template vue-ts 添加eslint eslint 初始化 npm init @eslint/config eslint初始化脚本,按自己的要求选择相应的eslint 配置,以下是我选择的配置项 ✔ How would you like to use ESLint? · style ✔ What type of modules does your project

    2024年02月08日
    浏览(49)
  • React 项目配置代码提交规范 ESLint、Pretttier、Husky、CommitLint

    React 项目配置代码提交规范 ESLint、Pretttier、Husky、CommitLint 前言 团队开发的成员越来越多,项目都是由多个人进行开发和维护,每个人的代码书写习惯和风格又不尽相同,commit 的提交log 也是乱七八糟,为以后的开发和维护增添了很多困难,所以规范和约束在多人协作下,就

    2024年04月15日
    浏览(48)
  • 【vue3+ts项目】配置eslint校验代码工具,eslint+prettier+stylelint

    package.json中 vite后面加上 --open 回答问题如下: 使用eslint仅检查语法,还是检查语法及错误,选第二个 使用的是什么模块,选第一个 项目使用的是什么框架,选vue 项目中使用TyoeScript ,选yes 项目运行在哪,选浏览器 创建的配置类型需要什么类型的,选Javascript 需要安装这些

    2024年02月09日
    浏览(78)
  • React18入门(第二篇)——React18+Ts项目配置husky、eslint、pretttier、commitLint

    我的项目版本如下: React: V18.2.0 Node.js: V16.14.0 TypeScript:最新版 工具: VsCode 本文将采用图文详解的方式,手把手带你快速完成在React项目中配置husky、prettier、commitLint,实现编码规范的统一,git提交规范的统一。 1.1 装包 1.2 ESLint 插件安装 1.3 创建命令并使用 新增命令 执行

    2024年02月08日
    浏览(52)
  • 【从零到一手撕脚手架 | 第三节】项目集成CommitLInt+ESLint+Prettier+StyleLint+LintStaged

    Hello大家好我是⛄,前两节教大家如何初始化一个脚手架项目以及如何封装Vue技术栈常用的工具库。本小节教大家如何向我们的脚手架中配置ESLint、Prettier、StyleLint、LintStage。帮助大家规范项目代码,能够更好的进行团队协作开发。 项目地址: GitHub :LonelySnowman/sv3-template 官方

    2024年04月16日
    浏览(63)
  • Vue3 + Vite 实现项目搭建

    首先嘞,这个博文就是简单的记录一下自己的对 Vue3 的学习,所以说呢,并不代表他是完全正确的。 创建 Vue3 项目有两种常见的方式,一种是想 vue2 版本一样使用脚手架工具创建,创建 vue3 项目的脚手架必须是4版本以上的,另一种方法就是使用 vite 创建,为什么使用 vite 呢

    2024年02月11日
    浏览(46)
  • vue3项目+TypeScript前端项目—— vue3搭建项目+eslint+husky

    今天来带大家从0开始搭建一个vue3版本的后台管理系统。一个项目要有统一的规范,需要使用eslint+stylelint+prettier来对我们的代码质量做检测和修复,需要使用husky来做commit拦截,需要使用commitlint来统一提交规范,需要使用preinstall来统一包管理工具。 下面我们就用这一套规范

    2024年02月22日
    浏览(78)
  • vue3之vite创建h5项目1(创建vite项目、配置IP访问项目、配置多环境变量与预览打包生产效果、配置别名)

    初始化项目模块 添加环境变量文件,每个文件写入配置,定义 env 环境变量前面必须加 VITE_ dev环境 test环境 prod环境 在项目根目录下创建 03-1:配置多环境变量之dev环境 .env.development 03-2:配置多环境变量之test环境 .env.test 03-3:配置多环境变量之prod环境 .env.production 03-4 修改

    2024年02月02日
    浏览(64)
  • vue3+Vite+TS项目,配置ESlint和Prettier

    实操过的有两种方式 1.vue脚手架 2.vite(推荐,也是尤大大团队研发) 具体怎么新建一个vue3项目就不多讲了,可以按照官方文档来 创建后的文件目录长这样 多提一句,vite也会随着时间不断迭代,后续项目结构可能还会发生变化,当前使用的vue版本 和vite版本也一并贴出来 下

    2024年04月15日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包