prettier+eslint+commitlint项目实践

团队代码风格统一一直是博主想干又没有时间去干的事情,刚好借着新项目搭建,尝试一下使用Eslint及Prettier工具提升一下项目代码的整体质量。本文在配置方面仅做简单的配置,流程熟悉可以参考Eslint及Prettier官方文档定制自己喜欢的标准。

安装Eslint包

1
npm install eslint -D

初始化Eslint

1
npm init @eslint/config

执行命令后会出现以下选项:(可以按照图片配置,也可以后面直接更改.eslintrc.cjs文件)
init详情
具体配置可以以自己项目为准,博主这里使用的是vite+vue3+js
安装完成之后项目的根目录会出现.eslintrc.cjs文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module.exports = {
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential"
],
"overrides": [
],
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"vue"
],
"rules": {
}
}

安装vite-plugin-eslint包

1
2
// 该包的作用是在vite运行时自动检测eslint规范,根据配置在终端显示未通过的校验代码
npm install vite-plugin-eslint -D

安装eslint-parser 及 @babel/core 包

1
2
3
// 该包的作用是允许eslint在babel转换的源代码上运行
npm install @babel/eslint-parser -D
npm install @babel/core -D

安装prettier相关包

1
2
3
npm install prettier -D
npm install eslint-config-prettier -D // eslint兼容的插件,将关闭eslint所有不必要或可能与Prettier冲突的规则
npm install eslint-plugin-prettier -D // eslint的prettier,将Prettier作为ESLint规则运行,并将差异作为单个ESLint问题报告。

安装vue-eslint-parser包

1
2
// 用于`.vue`文件的ESLint自定义解析器。
npm install vue-eslint-parser -D

配置.prettierrc

1
2
3
4
5
6
7
8
9
10
11
12
13
// .prettierrc, 配置不做过多说明,具体可查阅相关文档
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"trailingComma": "none",
"singleQuote": true,
"bracketSpacing": true,
"jsxBracketSameLine": false,
"endOfLine": "auto",
"arrowParens": "avoid"
}

配置.eslintrc.cjs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module.exports = {
env: {
browser: true,
es2021: true,
node: true
},
extends: [
'eslint:recommended', // eslint核心规则
'plugin:vue/vue3-essential', // 继承eslint-plugin-vue组件中的基础配置
'plugin:prettier/recommended', // 继承eslint-plugin-prettier组件中的基础配置
'eslint-config-prettier' // 处理配置兼容问题
],
parser: 'vue-eslint-parser', // 使用vue解析器
parserOptions: { // 设置支持的JavaScript语言选项
ecmaVersion: 'latest', // 指定EcmaScript的版本
sourceType: 'module', // script/module
ecmaFeatures: {
jsx: true
}
},
plugins:[
'vue', // eslint-plugin-vue缩写
'prettier' // eslint-plugin-prettier缩写
],
globals: {
// 添加全局变量,防止no-undef 规则发出警告
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly',
withDefaults: 'readonly'
},
rules: {
'no-console': 'warn',
'vue/multi-word-component-names': 'off' // extends中继承过来的属性,可以重新修改
...
}
}

VSCode配置

安装ESLint及Prettier插件
Eslint插件
Prettier插件

  1. 打开VSCode设置>用户>文本编辑器>格式化>勾选Format On Save

配置保存自动格式化
2. 搜索Prettier>勾选Require Config
配置方案文件
3.打开VSCode设置>用户>文本编辑器>Default Formatter>选择Prettier - Code formatter
配置默认格式化程序
4.ctr+shift+p打开首选项配置settings.json>添加eslint vue支持

1
2
3
4
5
6
7
...
"eslint.validate": [
"javascript",
"javascriptreact",
"vue"
],
...

特别提醒:每次修改完Eslint及Prettier配置最好重新启动VSCode,防止出现配置不生效的情况