vue3+vite+ts+eslint+prettier+stylelint+husky+lint-staged+commitlint+co

莫张周刘王  金牌会员 | 2024-7-14 02:07:22 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 552|帖子 552|积分 1656

vue3工程化搭建流程

vue3+vite+ts+eslint+prettier+stylelint+husky+lint-staged+commitlint+commitizen+cz-git
   工作当中我我们可以不搭建,可以直接用开源的架子,如vben等,但是我们一定要知道是如何搭建,当然一个好用的工程化项目还必要很多细节的配置,学习一下应付口试也是可以的。
  所用到的配置知识点



  • pnpm
  • vue3
  • vite
  • 阮一峰typescript
  • eslint
  • prettier
  • stylelint
  • husky
  • lint-staged
  • commitlint
  • Commitizen
  • cz-git
开发工具及插件配置

开发工具



  • vscode
插件



  • eslint
  • Prettier - Code formatter
  • Stylelint
  • Vue - Official
vscode --> settings.json添加下面配置

  1. // 关闭IDE自带的样式验证
  2.   "css.validate": false,
  3.   "less.validate": false,
  4.   "scss.validate": false,
  5.   // 指定stylelint生效的文件类型(尤其是vue文件)
  6.   "stylelint.validate": ["css", "postcss", "scss", "vue"],
  7.   // 启用eslint的格式化能力
  8.   "eslint.format.enable": true,
  9.   // eslint 会在检查出错误时,给出对应的文档链接地址
  10.   "eslint.codeAction.showDocumentation": {
  11.     "enable": true
  12.   },
  13.   // 指定 eslint 生效的文件类型(尤其是 vue 文件)。
  14.   "eslint.probe": ["javascript", "typescript", "vue"],
  15.   // 指定 eslint 的工作区,使每个子模块下的 .eslintignore 文件都能对当前目录生效。
  16.   "eslint.workingDirectories": [{ "mode": "auto" }],
  17.   // 设置默认格式化工具为 Prettier
  18.   "editor.defaultFormatter": "esbenp.prettier-vscode",
  19.   // 默认禁用自动格式化(手动格式化快捷键:Shift + Alt + F)
  20.   "editor.formatOnSave": true,
  21.   "editor.formatOnPaste": true,
  22.   // 启用自动代码修复功能,保存时触发 eslint 和 stylelint 的自动修复。
  23.   "editor.codeActionsOnSave": {
  24.     "source.fixAll.eslint": "explicit",
  25.     "source.fixAll.stylelint": "explicit"
  26.   },
  27.   // json、yaml 等配置文件保存时自动格式化
  28.   "[json]": {
  29.     "editor.formatOnSave": true
  30.   },
  31.   "[jsonc]": {
  32.     "editor.formatOnSave": true
  33.   },
  34.   "[yaml]": {
  35.     "editor.formatOnSave": true
  36.   },
  37.   "[vue]": {
  38.     "editor.defaultFormatter": "esbenp.prettier-vscode"
  39.   },
  40.   "[ignore]": {
  41.     "editor.defaultFormatter": "foxundermoon.shell-format"
  42.   },
  43.   "[shellscript]": {
  44.     "editor.defaultFormatter": "foxundermoon.shell-format"
  45.   },
  46.   "[javascript]": {
  47.     "editor.defaultFormatter": "esbenp.prettier-vscode"
  48.   }
复制代码
vite创建vue3项目

默认已经配置好pnpm,vite等环境。
  1. pnpm create vite my-vue-app --template vue-ts
复制代码
创建完的项目目录如下:

配置tsconfig

vite创建的项目给提供了两个tsconfig文件,一个是tsconfig.json,一个是tsconfig.node.json
为什么会有两个?这个就牵涉到了tsconfig的一个概念[项目引用](TypeScript 中文网: 文档 - 项目引用 (nodejs.cn)),vue3官方文档也有写到关于ts的配置

也就是说,要想我们的tsconfig配置更加灵活,我们一般会将整个工程分别为多个ts project


  • tsconfig.base.json 底子的配置,供其他配置文件继承
  • tsconfig.app.json 处置惩罚src目录下的源码文件,里面会有浏览器环境下也有的一些api
  • tsconfig.node.json 处置惩罚node环境下实验的脚本,如vite.config.ts
  • tsconfig.eslint.json 处置惩罚eslint关于ts解析的配置
  • tsconfig.json 通过references聚合全部的配置,然后给IDE利用,每个被聚合的文件要加compilerOptions.composite = true属性,才会被聚合在一起
新建相关文件,这个时间我们的项目目录如下:

tsconfig.base.json

  1. {
  2.   "compilerOptions": {
  3.     "rootDir": ".",
  4.     "baseUrl": ".",
  5.     "target": "ES2020",
  6.     "useDefineForClassFields": true,
  7.     "module": "ESNext",
  8.     "skipLibCheck": true,
  9.     /* Bundler mode */
  10.     "moduleResolution": "bundler",
  11.     "allowImportingTsExtensions": true,
  12.     "resolveJsonModule": true,
  13.     "isolatedModules": true,
  14.     "noEmit": true,
  15.     "jsx": "preserve",
  16.     "jsxImportSource": "vue",
  17.     /* Linting */
  18.     "strict": true,
  19.     "noUnusedLocals": true,
  20.     "noUnusedParameters": true,
  21.     "noFallthroughCasesInSwitch": true
  22.   }
  23. }
复制代码
tsconfig.app.json

  1. {
  2.   "extends": "./tsconfig.base.json",
  3.   "compilerOptions": {
  4.     "composite": true,
  5.     // 增加了浏览器特有的dom相关api
  6.     "lib": ["ESNext", "DOM", "DOM.Iterable"],
  7.     "types": ["node"],
  8.     "jsx": "preserve",
  9.     "jsxImportSource": "vue"
  10.   },
  11.   "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "types/*.d.ts"],
  12.   "exclude": ["node_modules/*", "**/__tests__/**/*", "**/*.js", "dist/*"]
  13. }
复制代码
tsconfig.node.app

  1. {
  2.   "extends": "./tsconfig.base.json",
  3.   "compilerOptions": {
  4.     "composite": true,
  5.     // 处理node脚本相关,不会有dom相关api
  6.     "lib": ["ESNext"],
  7.     "types": ["node"],
  8.     "allowJs": true
  9.   },
  10.   "include": ["vite.config.ts"]
  11. }
复制代码
tsconfig.eslint.json

  1. {
  2.   "extends": "./tsconfig.base.json",
  3.   "compilerOptions": {
  4.     "noEmit": true
  5.   },
  6.   "include": ["**/*", "**/.*.*"],
  7.   "exclude": ["dist/*", "node_modules/*"]
  8. }
复制代码
tsconfig.json

  1. {
  2.   "files": [],
  3.   "references": [{"path": "./tsconfig.app.json"},{ "path": "./tsconfig.node.json" }]
  4. }
复制代码
配置完之后我们发现tsconfig.node.json有标红,这个时间我们下载@types/node这个包即可
  1. pnpm i -D @types/node
复制代码

我们如果想要查看现实的编译选项或者包含的文件,我我们可以通过如下命令:
  1. npx tsc -p tsconfig.aoo.json--showConfig
复制代码

eslint配置

eslint利用8.x的版本,详细利用查看上面给出的文档
根本概念



  • 配置文件,本次搭建利用.eslintrc.cjs因为package.json里面type: module
  • 扩展配置文件 extends 可以省略配置名称中的eslint-config-前缀,如airbnb会被解析为eslint-config-airbnb
  • 配置插件 plugin 非范围包和范围包中都可以省略eslint-plugin-前缀

    • 非范围包
      1. {
      2.     // ...
      3.     "plugins": [
      4.         "jquery", // means eslint-plugin-jquery
      5.     ]
      6.     // ...
      7. }
      复制代码
    • 范围包
      1. {
      2.     // ...
      3.     "plugins": [
      4.         "@jquery/jquery", // means @jquery/eslint-plugin-jquery
      5.         "@foobar" // means @foobar/eslint-plugin
      6.     ]
      7.     // ...
      8. }
      复制代码

  • 配置规则 rules

    • off或0 关闭规则
    • warn或1启用并视作警告
    • error或2启用并视作错误

  • 配置解析器 parser 默认环境下eslint会利用Espree作为解析器,但是我们是vue项目会利用vue-eslint-parser作为解析器
  • 配置语言选项 env
    1. env: {
    2.     browser: true,
    3.     es2022: true,
    4.     node: true,
    5. }
    复制代码
  • 指定解析器选项
    1. {
    2.     "parserOptions": {
    3.         "ecmaVersion": "latest",
    4.         "sourceType": "module",
    5.         "ecmaFeatures": {
    6.             "jsx": true
    7.         }
    8.     },
    9.     "rules": {
    10.         "semi": "error"
    11.     }
    12. }
    复制代码
  • 忽略文件 利用.eslintignore
开始配置eslint

安装相关npm包

  1. pnpm i -D eslint@8.57.0
  2. pnpm i -D @typescript-eslint/parser @typescript-eslint/eslint-plugin vue-eslint-parser
  3. pnpm i -D eslint-plugin-import eslint-plugin-vue eslint-config-airbnb-base eslint-config-airbnb-typescript
  4. pnpm i -D eslint-plugin-prettier  eslint-config-prettier
  5. pnpm i -D eslint-define-config
复制代码


  • @typescript-eslint/parser eslint解析器,它答应eslint理解ts代码(eslint默认只能解析js代码)
  • @typescript-eslint/eslint-plugin eslint插件,包含了一些ts的设计规则,帮助开发者在开发的过程中避免一些常见的ts编程错误,并逼迫服从一定的编码标准
  • vue-eslint-parser eslint解析器,用于解析.vue文件中的<template>标签内的内容,如指令,插值表达式等,必要配合eslint-plugin-vue插件一起利用
  • eslint-plugin-vue 是一个专为 Vue.js 设计的 ESLint 插件,它提供了一套规则来帮助开发者遵照 Vue.js 的最佳实践和风格指南。这个插件可以与 vue-eslint-parser 结合利用,以支持 .vue 文件的 <template> 部门的语法查抄。
  • eslint-plugin-import 是一个 ESLint 插件,它提供了一系列规则来帮助你避免常见的问题,并逼迫实验最佳实践,尤其是在处置惩罚模块导入时。这个插件特别有用,因为它可以帮助你检测未利用的导入、错误的导入语句、缺失的模块扩展名等问题。eslint-config-airbnb-base eslint-config-airbnb-typescript这两个共享配置包必要用到eslint-plugin-import
  • eslint-config-airbnb-base eslint-config-airbnb-typescript 是两个差别的 ESLint 共享配置包,它们分别基于 Airbnb 的 JavaScript 和 TypeScript 编码规范。
  • eslint-define-config是一个用于创建 ESLint 配置的辅助工具,它提供了一个 defineConfig 函数,使得定义 ESLint 规则、插件和设置变得更加方便和范例安全。这个工具特别适合于必要在多个项目中重用相同 ESLint 配置的环境。
  • eslint-config-prettier 它的重要作用是关闭 ESLint 中与 Prettier 冲突的规则。Prettier 是一个流行的代码格式化工具,它会根据一定的风格规则主动格式化代码。由于 ESLint 也包含了一些格式化相关的规则,这些规则大概与 Prettier 的格式化风格不一致,因此大概会导致冲突。eslint-config-prettier 就是为相识决这个问题而设计的。
  • eslint-plugin-prettier 它将 Prettier 作为一个 ESLint 规则来运行,并将 Prettier 的输出与当前的代码进行比较
创建.eslintrc.cjs文件

  1. // @ts-check
  2. const { defineConfig } = require('eslint-define-config');
  3. const path = require('node:path');
  4. /// <reference types="@eslint-types/typescript-eslint" />
  5. module.exports = defineConfig({
  6.   // 告诉eslint这个就是搁那配置文件,不需要在去上层查找
  7.   root: true,
  8.   // 配置全局环境api
  9.   env: {
  10.     browser: true,
  11.     node: true,
  12.     es2022: true,
  13.   },
  14.   // 后续如果用到jquery等会用到
  15.   globals: {
  16.     // $: "readonly",
  17.   },
  18.   // 共享配置
  19.   extends: [
  20.     'airbnb-base', // eslint-config-airbnb-base
  21.     'airbnb-typescript/base', // eslint-config-airbnb-typescript
  22.     'plugin:vue/vue3-recommended', // eslint-plugin-vue 具体为什么这么配置可以参考文档
  23.     'eslint-config-prettier',
  24.   ],
  25.   plugins: ['vue', 'prettier', '@typescript-eslint'],
  26.   // 配置vue解析器
  27.   parser: 'vue-eslint-parser',
  28.   // 指定ts的解析器
  29.   parserOptions: {
  30.     parser: '@typescript-eslint/parser',
  31.     // ts解析器里面的属性
  32.     project: path.resolve(__dirname, './tsconfig.eslint.json'),
  33.     ecmaVersion: 13,
  34.     sourceType: 'module',
  35.     extraFileExtensions: ['.vue'],
  36.     ecmaFeatures: {
  37.       jsx: true,
  38.     },
  39.   },
  40.   rules: {
  41.     'import/no-extraneous-dependencies': 'off',
  42.     'import/prefer-default-export': 'off',
  43.     // vue 允许单单词组件名
  44.     'vue/multi-word-component-names': 'off',
  45.     'operator-linebreak': ['error', 'after'],
  46.     'class-methods-use-this': 'off',
  47.     // 允许使用 ++
  48.     'no-plusplus': 'off',
  49.     'no-spaced-func': 'off',
  50.     // 换行符不作约束
  51.     'linebreak-style': 'off',
  52.   },
  53.   overrides: [
  54.     {
  55.       files: ['vite.config.ts'],
  56.       rules: {
  57.         'no-console': 'off',
  58.       },
  59.     },
  60.   ],
  61. });
复制代码
创建.eslintignore

eslint默认忽略对.开头文件的查抄,对于一些其他配置文件,我们必要加!反向声明忽略
  1. dist
  2. node_modules
  3. public
  4. .husky
  5. .bin
  6. .vscode
  7. .idea
  8. *.sh
  9. *.md
  10. .DS_Store
  11. !.eslintrc.js
  12. !.stylelintrc.js
  13. !.prettierrc.js
  14. !.lintstagedrc.js
  15. !.commitlintrc.js
复制代码
配置命令

在package.json中的scripts中添加如下命令
  1. # 检测文件
  2. "lint:eslint": "eslint ."
  3. # 检测文件并自动 fix
  4. "fix:eslint": "eslint --ext .js,.jsx,.ts,.tsx,.vue --fix ./"
复制代码
然后运行

阐明我们的配置已经生效
prettier配置

是一个流行的代码格式化工具,它支持多种编程语言和文件范例,旨在提供一个统一的代码风格,以减少在代码检察过程中关于代码样式的讨论
安装相关npm包

  1. pnpm i -D prettier
复制代码
新建prettier.config.json

  1. {
  2.   "printWidth": 80,
  3.   "tabWidth": 2,
  4.   "useTabs": false,
  5.   "semi": true,
  6.   "singleQuote": true,
  7.   "quoteProps": "as-needed",
  8.   "jsxSingleQuote": false,
  9.   "trailingComma": "es5",
  10.   "bracketSpacing": true,
  11.   "jsxBracketSameLine": false,
  12.   "bracketSameLine": false,
  13.   "arrowParens": "avoid",
  14.   "endOfLine": "auto",
  15.   "embeddedLanguageFormatting": "auto",
  16.   "vueIndentScriptAndStyle": true,
  17.   "singleAttributePerLine": false,
  18.   "htmlWhitespaceSensitivity": "css",
  19.   "requirePragma": false,
  20.   "insertPragma": false,
  21.   "proseWrap": "preserve"
  22. }
复制代码
新建.prettierignore忽略文件

  1. .eslintrc-auto-import.json
  2. /types/components.d.ts
  3. /types/auto-import.d.ts
  4. node_modules
  5. .DS_Store
  6. dist
  7. dist-ssr
  8. .git
  9. .prettierignore
  10. .eslintignore
  11. .gitignore
  12. *.wasm
  13. *.txt
  14. *.png
  15. *.jpg
  16. *.jpeg
  17. *.gif
  18. *.bmp
  19. *.svg
  20. *.ttf
  21. *.ico
  22. *.lock
  23. *.sh
  24. *.md
  25. *.woff
  26. .browserslistrc
  27. *.local
  28. *debug.log*
  29. *error.log*
  30. *-lock.json
  31. .idea
  32. .vscode
  33. *.suo
  34. *.ntvs*
  35. *.njsproj
  36. *.sln
复制代码
配置命令

  1. # 基础命令
  2. "prettier": "prettier --no-editorconfig --config-precedence prefer-file "**/*.{js,cjs,mjs,ts,cts,mts,json,jsonc,jsx,tsx,css,less,scss,styl,vue,html,md}"",
  3. # prettier 检测文件
  4. "lint:prettier": "npm run prettier -- --check",
  5. # prettier 检测文件并fix
  6. "fix:prettier": "npm run prettier -- --write"
复制代码
stylelint 配置

是一个强大的、现代化的 CSS 代码查抄工具,它可以帮助开发者避免在样式表中出现错误,并保持一致的编码风格。
安装 npm 包

可以把下面的包以及版本好,拷贝到package.json的devDependencies中,实验pnpm i下载
  1. "postcss": "^8.4.31",
  2. "postcss-scss": "^4.0.9",
  3. "postcss-html": "^1.5.0",
  4. "sass": "^1.77.5",
  5. "stylelint": "^15.10.3",
  6. "stylelint-config-html": "^1.1.0",
  7. "stylelint-config-prettier": "^9.0.5",
  8. "stylelint-config-recommended-scss": "^13.0.0",
  9. "stylelint-config-recommended-vue": "^1.5.0",
  10. "stylelint-config-standard": "^34.0.0",
  11. "stylelint-config-standard-scss": "^11.0.0",
  12. "stylelint-order": "^6.0.3",
  13. "stylelint-scss": "^5.2.1"
复制代码
新建stylelint.config.mjs

  1. export default {
  2.   plugins: ['stylelint-order'],
  3.   extends: [
  4.     "stylelint-config-standard", // 配置 stylelint 拓展插件
  5.     "stylelint-config-html/vue", // 配置 vue 中 template 样式格式化
  6.     "stylelint-config-standard-scss", // 配置 stylelint scss 插件
  7.     "stylelint-config-recommended-vue/scss", // 配置 vue 中 scss 样式格式化
  8.   ],
  9.   ignoreFiles: [
  10.     '**/*.js',
  11.     '**/*.cjs',
  12.     '**/*.jsx',
  13.     '**/*.tsx',
  14.     '**/*.ts',
  15.     '**/*.json',
  16.     '**/*.md',
  17.     '**/*.yaml',
  18.     'node_modules/',
  19.     'dist/',
  20.     'public/',
  21.     'docs/',
  22.   ],
  23.   overrides: [
  24.     {
  25.       files: ['**/*.(scss|css)'],
  26.       customSyntax: 'postcss-scss',
  27.     },
  28.     {
  29.       files: ['**/*.(html|vue)'],
  30.       customSyntax: 'postcss-html',
  31.     },
  32.   ],
  33.   rules: {
  34.     "scss/at-import-partial-extension": null,
  35.     'scss/dollar-variable-pattern': null, // 解决类名不允许下划线
  36.     'scss/double-slash-comment-whitespace-inside': null,// 解决双斜杠注释后要有一个空格
  37.     'selector-class-pattern': null,
  38.     'block-no-empty': null,
  39.     'no-empty-source': null,
  40.     'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
  41.     'selector-pseudo-element-no-unknown': [
  42.       true,
  43.       {
  44.         ignorePseudoElements: ['v-deep'],
  45.       },
  46.     ],
  47.     'selector-pseudo-class-no-unknown': [
  48.       true,
  49.       {
  50.         ignorePseudoClasses: ['deep'],
  51.       },
  52.     ],
  53.     'font-family-no-missing-generic-family-keyword': null,
  54.     'no-duplicate-selectors': null,
  55.     'selector-id-pattern': null, // 指定id选择器的模式
  56.     'custom-property-pattern': null, // 为自定义属性指定模式。
  57.     'no-invalid-double-slash-comments': null, // 禁止使用双斜杠注释(关闭)
  58.     'at-rule-no-unknown': [
  59.       true,
  60.       {
  61.         ignoreAtRules: ['mixin', 'if', 'else', 'include'],
  62.       },
  63.     ],
  64.     'property-no-unknown': [
  65.       true,
  66.       {
  67.         ignoreProperties: ['line-clamp'],
  68.       },
  69.     ],
  70.     'indentation': [2],
  71.     'order/properties-order': [ // 规则顺序
  72.       'position',
  73.       'content',
  74.       'top',
  75.       'right',
  76.       'bottom',
  77.       'left',
  78.       'float',
  79.       'display',
  80.       'margin',
  81.       'margin-top',
  82.       'margin-right',
  83.       'margin-bottom',
  84.       'margin-left',
  85.       'margin-collapse',
  86.       'margin-top-collapse',
  87.       'margin-right-collapse',
  88.       'margin-bottom-collapse',
  89.       'margin-left-collapse',
  90.       'border',
  91.       'border-radius',
  92.       'outline',
  93.       'outline-offset',
  94.       'padding',
  95.       'padding-top',
  96.       'padding-right',
  97.       'padding-bottom',
  98.       'padding-left',
  99.       'width',
  100.       'height',
  101.       'max-width',
  102.       'max-height',
  103.       'min-width',
  104.       'min-height',
  105.       'clip',
  106.       'font',
  107.       'font-family',
  108.       'font-size',
  109.       'font-smoothing',
  110.       'osx-font-smoothing',
  111.       'font-style',
  112.       'font-weight',
  113.       'line-height',
  114.       'letter-spacing',
  115.       'word-spacing',
  116.       'text-align',
  117.       'text-decoration',
  118.       'text-indent',
  119.       'text-overflow',
  120.       'text-rendering',
  121.       'text-size-adjust',
  122.       'text-shadow',
  123.       'text-transform',
  124.       'word-break',
  125.       'word-wrap',
  126.       'white-space',
  127.       'vertical-align',
  128.       'list-style',
  129.       'list-style-type',
  130.       'list-style-position',
  131.       'list-style-image',
  132.       'pointer-events',
  133.       'opacity',
  134.       'filter',
  135.       'visibility',
  136.       'size',
  137.       'transform',
  138.       'background',
  139.       'background-color',
  140.       'color',
  141.       'clear',
  142.       'cursor',
  143.       'overflow',
  144.       'overflow-x',
  145.       'overflow-y',
  146.       'z-index',
  147.     ],
  148.   },
  149. }
复制代码
新建.stylelintignore文件

不必要忽略的可以自行删除
  1. .eslintrc-auto-import.json
  2. /types/components.d.ts
  3. /types/auto-import.d.ts
  4. node_modules
  5. .DS_Store
  6. dist
  7. dist-ssr
  8. .git
  9. .prettierignore
  10. .eslintignore
  11. .gitignore
  12. /bin
  13. /docs
  14. .husky
  15. Dockerfile
  16. *.wasm
  17. *.txt
  18. *.png
  19. *.jpg
  20. *.jpeg
  21. *.gif
  22. *.bmp
  23. *.svg
  24. *.ttf
  25. *.ico
  26. *.lock
  27. *.sh
  28. *.md
  29. *.woff
  30. .browserslistrcf
  31. *.local
  32. *debug.log*
  33. *error.log*
  34. *lock.json
  35. *.js
  36. *.jsx
  37. *.ts
  38. *.tsx
  39. .idea
  40. .vscode
  41. *.suo
  42. *.ntvs*
  43. *.njsproj
  44. *.sln
  45. *.sw?
复制代码
添加命令

  1. "lint:stylelint": "stylelint "**/*.{css,scss,less,styl,postcss,vue}"",
  2. "fix:stylelint": "npm run lint:stylelint -- --fix"
复制代码
Husky配置

husky是git的钩子函数,可以设置在git各个阶段触发,目前我们必要设置的两个钩子是:
git的全部钩子


  • pre-commit
  • commit-msg
v8-v9更新内容

配置.git

  1. git init
复制代码
会天生一个潜伏的.git文件夹
安装husky

  1. pnpm i -D husky
  2. npx husky init
复制代码

实验完npx husky init之前要先配置好git,实验完,会天生一个.husky文件夹
init 命令简化了项目中的 husky 设置。它会在 .husky/ 中创建 pre-commit 脚本,并更新 package.json 中的 prepare 脚本。随后可根据你的工作流进行修改。

lint-staged配置

lint-staged 是一个在 git add 到暂存区的文件运行 linters (ESLint/Prettier/StyleLint) 的工具,避免在 git commit 提交时在整个项目实验。lint-staged 可以让你当前的代码查抄 只查抄本次修改更新的代码,并在出现错误的时间,主动修复而且推送
安装lint-staged

  1. pnpm i lint-staged  -D
复制代码
检测/格式化配置



  • 方式一:在package.json中添加
    1. "lint-staged": {
    2.     "*.{js,ts,vue}": [
    3.       "eslint --fix",
    4.       "prettier --write",
    5.       "git add"
    6.     ],
    7.     "*.{cjs,json}": [
    8.       "prettier --write"
    9.     ],
    10.     "*.{vue,html}": [
    11.       "eslint --fix",
    12.       "prettier --write",
    13.       "stylelint --fix"
    14.     ],
    15.     "*.{scss,css}": [
    16.       "stylelint --fix",
    17.       "prettier --write"
    18.     ],
    19.     "*.md": [
    20.       "prettier --write"
    21.     ]
    22.   }
    复制代码
  • 方式二: 新建一个lint-staged.config.cjs文件,教程里面用的是这个方案
    1. module.exports = {
    2.   "*.{js,cjs,mjs,jsx,ts,cts,mts,tsx,vue}": ["eslint"],
    3.   "*.{css,scss,less,styl,postcss,vue,html}": ["stylelint"],
    4. };
    复制代码
    scripts中添加命令

    1. "lint:lint-staged": "lint-staged"
    复制代码
    修改.husky中pre-commit钩子函数配置

    1. #!/bin/sh
    2. . "$(dirname "$0")/_/husky.sh"
    3. npm run lint:lint-staged
    复制代码

    结果如下,则配置生效,(前提要先git add .)

    commitlint配置

    上面配置好了husky以及lint-staged之后,我们想要再提交commit的时间符合一定的标准如

安装npm包

  1. npm install --save-dev @commitlint/config-conventional @commitlint/cli
复制代码
新建commitlint.config.cjs

  1. module.exports = {
  2.   // 继承的规则
  3.   extends: ['@commitlint/config-conventional'],
  4.    // @see: https://commitlint.js.org/#/reference-rules
  5.   rules: {
  6.     'subject-case': [0], // subject大小写不做校验
  7.     // 类型枚举,git提交type必须是以下类型
  8.     'type-enum': [
  9.       // 当前验证的错误级别
  10.       2,
  11.       // 在什么情况下进行验证,always表示一直进行验证
  12.       'always',
  13.       [
  14.         'feat', // 新增功能
  15.         'fix', // 修复缺陷
  16.         'docs', // 文档变更
  17.         'style', // 代码格式(不影响功能,例如空格、分号等格式修正)
  18.         'refactor', // 代码重构(不包括 bug 修复、功能新增)
  19.         'perf', // 性能优化
  20.         'test', // 添加疏漏测试或已有测试改动
  21.         'build', // 构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)
  22.         'ci', // 修改 CI 配置、脚本
  23.         'revert', // 回滚 commit
  24.         'chore' // 对构建过程或辅助工具和库的更改(不影响源文件、测试用例)
  25.       ]
  26.     ]
  27.   }
  28. }
复制代码
添加commit提交信息校验的钩子

添加方式是husky9.x版本,husky那边要v8,v9更新的日志
  1. echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
复制代码
运行完之后会在.husky中天生一个commit-msg文件,或者手动添加,直接把下面的命令拷贝到commit-msg当中
  1. #!/bin/sh
  2. . "$(dirname "$0")/_/husky.sh"
  3. npx --no-install commitlint --edit "$1"
复制代码
windows(win11)下面通过命令天生运行的时间有问题,所以直接手动添加内容


然后运行git commit -m '测试commit钩子'

阐明我们的配置已经生效,可以看到提示我们sunject,type不能为空,修改一下git commit -m "feat: 规范的提交" 可以看到下面的图里没有了报错
正确的提交格式: <type>(<scope>): <subject>

但是我们希望再提交的时间不必要手写这些type,subject,怎么办?
commitizen & cz-git配置



  • commitizen 基于Node.js的 git commit 命令行工具,辅助天生标准化规范化的 commit message
  • cz-git 一款工程性更强,轻量级,高度自定义,标准输出格式的 commitizen 适配器
安装npm包

  1. # 全局安装
  2. pnpm i -g commitizen
  3. pnpm i -D cz-git
复制代码
package.json中添加config,用来指定适配器

  1. "config": {
  2.     "commitizen": {
  3.       "path": "node_modules/cz-git"
  4.     }
  5.   }
复制代码
cz-git与commitlint进行联动给予校验信息,所以可以编写于commitlint.config.cjs中
[code]module.exports = {
  // 继承的规则
  extends: ["@commitlint/config-conventional"],
  // @see: https://commitlint.js.org/#/reference-rules
  rules: {
    "subject-case": [0], // subject大小写不做校验

    // 类型枚举,git提交type必须是以下类型
    "type-enum": [
      2,
      "always",
      [
        "feat", // 新增功能
        "fix", // 修复缺陷
        "docs", // 文档变更
        "style", // 代码格式(不影响功能,例如空格、分号等格式修正)
        "refactor", // 代码重构(不包括 bug 修复、功能新增)
        "perf", // 性能优化
        "test", // 添加疏漏测试或已有测试改动
        "build", // 构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)
        "ci", // 修改 CI 配置、脚本
        "revert", // 回滚 commit
        "chore", // 对构建过程或辅助工具和库的更改(不影响源文件、测试用例)
      ],
    ],
  },
  prompt: {
    messages: {
      type: "选择你要提交的类型 :",
      scope: "选择一个提交范围(可选):",
      customScope: "请输入自定义的提交范围 :",
      subject: "填写简短精炼的变更描述 :\n",
      body: '填写更加详细的变更描述(可选)。使用 "|" 换行 :\n',
      breaking: '列举非兼容性重大的变更(可选)。使用 "|" 换行 :\n',
      footerPrefixesSelect: "选择关联issue前缀(可选):",
      customFooterPrefix: "输入自定义issue前缀 :",
      footer: "列举关联issue (可选) 例如: #31, #I3244 :\n",
      generatingByAI: "正在通过 AI 生成你的提交简短描述...",
      generatedSelectByAI: "选择一个 AI 生成的简短描述:",
      confirmCommit: "是否提交或修改commit ?",
    },
    // prettier-ignore
    types: [
      { value: "feat",     name: "特性:     ✨  新增功能", emoji: ":sparkles:" },
      { value: "fix",      name: "修复:     

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

莫张周刘王

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表