Vue3 + Vite 项目 ESLint 配置指南

最近在搞一个 Vue3 + Vite 的项目,想着给项目加上 ESLint,结果发现 ESLint 现在推荐用新的 flat config 格式了,跟之前那种 .eslintrc.js 的写法完全不一样。折腾了一阵子终于搞定,记录一下配置过程,希望能帮到同样遇到这个问题的小伙伴。

安装依赖

首先当然是装 ESLint 和相关插件啦:

1
npm install -D eslint @eslint/js eslint-plugin-vue

这里简单说一下装的几个包都是干啥的:

  • eslint - ESLint 核心,不用说
  • eslint/js - JavaScript 官方推荐的规则集
  • eslint-plugin-vue - Vue 官方的 ESLint 插件,专门检查 Vue 组件的

写配置文件

ESLint 现在推荐使用 flat config 格式,配置文件名是 eslint.config.js,写法跟以前差别挺大的。

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
39
import js from '@eslint/js'
import pluginVue from 'eslint-plugin-vue'

export default [
{
name: 'ignores',
ignores: [
'dist/**',
'node_modules/**',
]
},
js.configs.recommended,
...pluginVue.configs['flat/recommended'],
{
languageOptions: {
globals: {
localStorage: 'readonly',
sessionStorage: 'readonly',
window: 'readonly',
document: 'readonly',
console: 'readonly',
setTimeout: 'readonly',
clearTimeout: 'readonly',
setInterval: 'readonly',
clearInterval: 'readonly',
fetch: 'readonly',
URL: 'readonly',
process: 'readonly'
}
},
rules: {
'vue/multi-word-component-names': 'off',
'vue/no-v-html': 'warn',
'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'no-console': 'off',
'no-debugger': 'warn'
}
}
]

这里有几个坑说一下:

第一个坑:一定要在配置里声明浏览器全局变量!不然 ESLint 会报 localStorage is not defined 之类的错误。上面配置里的 globals 就是干这个的。

第二个坑ignores 要放在第一个配置对象里单独写,不能跟其他配置混在一起。

自定义规则说明

  • vue/multi-word-component-names: 'off' - 这个规则要求组件名必须是多单词的,我习惯用单词组件名,干脆关掉了
  • vue/no-v-html: 'warn' - 用 v-html 有 XSS 风险,改成 warn 提醒自己注意
  • no-unused-vars - 未使用变量改成警告,argsIgnorePattern: '^_' 表示以 _ 开头的参数可以忽略(有时候回调函数的参数不用但又必须写在前面)

配置 npm 脚本

package.json 里加上:

1
2
3
4
5
6
{
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix"
}
}

这样就可以用 npm run lint 检查代码,用 npm run lint:fix 自动修复能修的问题。

集成到 Vite

光有命令行检查还不够,开发的时候能实时看到问题更方便。装个 vite-plugin-eslint:

1
npm install -D vite-plugin-eslint

然后在 vite.config.js 里加上:

1
2
3
4
5
6
7
8
import eslint from 'vite-plugin-eslint'

export default defineConfig({
plugins: [
vue(),
eslint(),
],
})

这样 Vite 开发服务器启动后,代码有问题会直接在页面上弹出来,再也不用手动跑 lint 命令了。

一些常见问题

中文全角空格报错

有时候复制代码会带上中文全角空格,ESLint 会报 no-irregular-whitespace。这个一般 IDE 能看出来,注意一下就行。

未使用的导入

no-unused-vars 这个规则经常会报,比如:

1
2
3
4
5
// 报错:nextTick 未使用
import { nextTick, ref } from 'vue'

// 改成这样
import { ref } from 'vue'

如果有些变量确实暂时不用但想留着,可以在变量名前加个下划线 _,因为上面配置了 argsIgnorePattern: '^_'

小结

ESLint 配置这东西,一开始看着挺麻烦的,配好之后真的能避免很多低级错误。尤其是多人协作的项目,统一代码风格太重要了。flat config 虽然写法变了,但配置逻辑其实更清晰了,习惯了就好。

如果这篇对你有帮助,欢迎留言交流~