Article directory
Introduction
What to do: This article will take you from scratch to configure
husky
andstylelint
complete the mandatory verification before submitting the code to git to ensure code style and consistency.
Technology stack: Vue3 + TypeScript + Vite
1. Project environment
1.1 node.js v16.0.0 and above (I v16.14.1)
// 查看node 版本 : 打开小黑窗输入 node -v
node -v
1.2 pnpm v8.0.0 and above (I v8.6.6)
// 查看pnpm 版本 : 打开小黑窗输入 pnpm -v
pnpm -v
2. Create a project
2.1 Install pnpm
npm i pnpm -g
2.2 Create a project - no need to go into details
pnpm create vite '项目名称'
3. Configure eslint
3.1 Install eslint
pnpm i eslint -D
3.2 Generate eslint configuration file
pnpm eslint --init
After running the command, a file will be generated in the root directory .eslintrc.cjs
with the following code:
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 Improve the rules object in the .eslintrc.cjs file
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 Create a new ignore file
Create a new file in the project root directory .eslintignore
and write the following code:
dist
node_modules
3.5 Add script
Add two lines of commands in the packjson.json
Medium fieldscript
"lint": "eslint src",
"fix": "eslint src --fix"
3.6 Check whether it is effective
main.ts
Use the data type in and var
run the pnpm run lint command on the terminal. The following error message appears. eslint
The installation and configuration are successful.
Then try running the repair command pnpm run fix
. The repair is successful, proving that the configuration is successful.
4. Configure prettier
In our project,
eslint
we should be mainly responsible for syntax verification andprettier
code formatting.
4.1 Install prettier
pnpm install -D eslint-plugin-prettier prettier eslint-config-prettier
4.2 Run pnpm run lint
After the packaging is completed, run pnpm run lint
the command in the terminal to check whether this packaging affects the project.
pnpm run lint
If you run pnpm run lint
the command, you will get an error like this:
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
If an error similar to the above is reported, run the following command. If no error is reported, proceed to the next step:
pnpm install prettier@^2.4.0 -D
4.3 Create a new prettier configuration file
Create a new .prettierrc.json
file in the root directory and fill in the following code:
{
"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
}
Description of each file:
{
"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 Create a new ignore file
Create a new .prettierignore
file in the root directory and fill in the following code:
/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*
4.5 Improve the .eslintrc.cjs file
'plugin:prettier/recommended',
Add main.ts
a console sentence for testing, and then run it pnpm run lint
. You can see that the console gives prompts.
4.6 Add script
Add a line of command in the packjson.json
file's fieldscript
"format": "prettier --write \"./**/*.{html,vue,js,ts,json,md}\" "
Run pnpm run format
and you will see that all allowed files have been formatted.
5. Configure stylelint
stylelint
It is a formatting tool for css. Can format css code, check css syntax errors and unreasonable writing, specify css writing order, etc.
5.1 Install stylelint
In this project, scss is used as the preprocessor and the following dependencies are installed:
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 After packaging is completed
5.1 After the command execution is completed, if a warning similar to the following is reported, you can ignore it and continue to step 5.2.
└─┬ stylelint-config-prettier 9.0.5
└── ✕ unmet peer stylelint@“>= 11.x < 15”: found 15.10.1
5.3 Create a new stylelint configuration file
Create a new one in the project root directory .stylelintrc.cjs
and fill in the following code:
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 Create a new stylelint ignore file
Create a new file in the project root directory .stylelintignore
and fill in the following code:
/node_modules/*
/dist/*
/html/*
/public/*
5.5 Add script
Add a command in the packjson.json
file's fieldscript
"lint:style": "stylelint src/**/*.{css,scss,vue} --cache --fix"
6. Configure husky
6.1 Install husky
pnpm install -D husky
6.2 Generate husky configuration file
Note: Before executing this command, you must first
git init
or download this project链接到远程仓库
(github, gitee, etc.)
npx husky-init
After executing this command, a .husky directory will be generated in the root directory, and there will be a pre-commit file under this directory 内容如下
. The commands in this file will be executed when we execute commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm format
7. Configure commitlint
Configure commit information when submitting git, and submit git submission specifications uniformly
7.1 Install commitlint
pnpm add @commitlint/config-conventional @commitlint/cli -D
7.2 Create a new commitlint configuration file
Create a new commitlint.config.cjs file in the project root directory and fill in the following code:
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],
},
}
Configuration instructions:
'feat', //新特性、新功能
'fix', //修改bug
'docs', //文档修改
'style', //代码格式修改, 注意不是 css 修改
'refactor', //代码重构
'perf', //优化相关,比如提升性能、体验
'test', //测试用例修改
'chore', //其他修改, 比如改变构建流程、或者增加依赖库、工具等
'revert', //回滚到上一个版本
'build', //编译相关的修改,例如发布版本、对项目构建或者依赖的改动
7.3 Add script
Add a command in the packjson.json
file's fieldscript
"commitlint": "commitlint --config commitlint.config.cjs -e -V"
7.4 Use with husky
npx husky add .husky/commit-msg
Add the following command to commit-msg in the husky folder in the root directory
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm commitlint
7.5 Submission specifications
Submit demonstration: git commit -m 'feat: New product page query function'
is not only usedfeat
as a prefix, but also other prefixes can be used. See step 7.2 for details.