本教程将指导你一步步在 Vue 项目中安装和配置 @antfu/eslint-config
,实现代码规范化与自动格式化。
前置条件
确保你的 Node.js 版本满足要求:Node.js >= 23 。
若版本不符合,可使用 nvm 管理 Node.js 版本,方便一键切换。
安装步骤
1. 安装 VS Code ESLint 插件
在 VS Code 扩展市场中搜索并安装 ESLint 插件,用于实时检测代码规范问题。
2. 安装 @antfu/eslint-config
运行以下命令安装最新版本的 @antfu/eslint-config
:
bash
pnpm dlx @antfu/eslint-config@latest
安装过程中会进入交互式配置界面:
-
选择技术栈 :选择
Vue
(按空格勾选)。
-
自动格式化 :勾选"自动格式化"选项。如果小的项目使用 UnoCSS,可勾选
UnoCSS
以启用类名自动排序。
-
VS Code 配置 :勾选生成
settings.json
,这会为当前项目创建专属的 VS Code 配置文件。
注意 :@antfu/eslint-config
内置格式化功能,无需 Prettier,会自动禁用 Prettier 插件。
自定义配置
默认配置下,Vue 文件中的 <style>
块(CSS/LESS/SCSS)不会自动格式化。需要额外配置 eslint.config.mjs
文件以启用格式化支持。
配置示例
在项目根目录创建或修改 eslint.config.mjs
:
javascript
import antfu from '@antfu/eslint-config'
export default antfu({
formatters: {
css: true, // 启用 CSS、LESS、SCSS 及 Vue <style> 块格式化
html: true, // 启用 HTML 文件格式化
},
unocss: true, // 启用 UnoCSS 类名排序(如果使用 UnoCSS)
vue: true, // 启用 Vue 相关规则
}, {
rules: {
'antfu/if-newline': 'off', // 关闭 if 语句强制换行
'no-async-promise-executor': 'off', // 允许 Promise 构造函数使用 async
'perfectionist/sort-imports': [ // 配置导入排序
'error',
{
customGroups: {
type: {
'vue-type': ['^vue$', '^vue-.+', '^@vue/.+'],
},
value: {
vue: ['^vue$', '^vue-.+', '^@vue/.+'], // Vue 相关库
components: ['^@/components/.+', '@/tmui/.+'], // 组件
stores: ['^@/store/.+'], // 状态管理
utils: ['^@/utils/.+'], // 工具函数
constants: ['^@/constants/.+'], // 常量
hooks: ['^@/hooks/.+'], // 自定义 hooks
api: ['^@/service/.+'], // API 服务
},
},
environment: 'node',
groups: [
// 类型导入
['external-type', 'builtin-type', 'type'],
'vue-type',
['parent-type', 'sibling-type', 'index-type'],
['internal-type'],
// 值导入
'builtin',
'vue',
'external',
'internal',
// 内部模块
'components',
'stores',
'utils',
'constants',
'hooks',
'api',
// 其他
['parent', 'sibling', 'index'],
'side-effect',
'side-effect-style',
'style',
'object',
'unknown',
],
internalPattern: ['^@/.+'], // 内部模块路径匹配
newlinesBetween: 'always', // 导入组之间空行
order: 'asc', // 升序排序
type: 'natural', // 自然排序
},
],
},
})
配置说明
formatters.css
和formatters.html
:启用 CSS 和 HTML 文件(包括 Vue 的<style>
块)的自动格式化。unocss
:启用 UnoCSS 类名排序(仅在使用 UnoCSS 时启用)。vue
:启用 Vue 特定规则。rules
:自定义规则,例如禁用if
语句换行、允许async
Promise 构造函数、配置导入排序等。
完成安装
-
安装项目依赖:
bashpnpm install
-
重启 VS Code,确保配置生效。
批量修复 ESLint 问题
运行以下命令批量修复指定目录中的 ESLint 问题:
bash
# 修复 src 目录
npx eslint --fix --ext .js,.ts,.vue src
# 修复 src/components 目录
npx eslint --fix --ext .js,.ts,.vue src/components
注意事项
- Node.js 版本:确保使用 Node.js >= 23,否则可能出现兼容性问题。推荐使用 nvm 管理 Node.js 版本。
- Prettier 禁用 :
@antfu/eslint-config
内置格式化功能,无需 Prettier,安装后会自动禁用 Prettier 插件。 - UnoCSS:仅在项目中使用 UnoCSS 时启用相关配置。