跳转到内容

快速开始 ​

eslint-plugin-vue-perfectionist 为 Vue 3 脚本和模板提供可配置的 ESLint 规则。 按以下步骤注册插件、启用规则并运行检查。

开发状态

在首次稳定版本发布前,API 可能发生变化。升级时请查阅更新日志。

安装 ​

本插件面向 Vue >=3.5.42 <4,包括版本匹配的 SFC 编译器和 SSR 渲染器。更早版本不在支持范围内。Vue 声明为可选对等依赖,运行 ESLint 时不会加载 Vue 运行时。

本包采用 ESM 格式,将 ESLint ^10.0.0 和 vue-eslint-parser ^10.0.0 声明为对等依赖。请一并安装:

shell
pnpm add -D eslint eslint-plugin-vue-perfectionist vue-eslint-parser
shell
npm i -D eslint eslint-plugin-vue-perfectionist vue-eslint-parser
shell
yarn add -D eslint eslint-plugin-vue-perfectionist vue-eslint-parser

如果使用 TypeScript 单文件组件,还需要安装脚本解析器和 TypeScript:

shell
pnpm add -D @typescript-eslint/parser typescript@6
shell
npm i -D @typescript-eslint/parser typescript@6
shell
yarn add -D @typescript-eslint/parser typescript@6

基本用法 ​

在 eslint.config.mjs 中注册插件并启用所需规则。本插件仅提供规则,不提供内置配置。以下示例支持 JavaScript 和 TypeScript Vue 单文件组件:

eslint.config.mjs
js
import tsParser from '@typescript-eslint/parser'
import { defineConfig } from 'eslint/config'
import vuePerfectionist from 'eslint-plugin-vue-perfectionist'
import vueParser from 'vue-eslint-parser'

export default defineConfig([
  {
    files: ['**/*.vue'],
    languageOptions: {
      parser: vueParser,
      parserOptions: {
        parser: tsParser,
      },
    },
    plugins: {
      'vue-perfectionist': vuePerfectionist,
    },
    rules: {
      'vue-perfectionist/callback-style': 'error',
      'vue-perfectionist/define-macros-newline': 'error',
      'vue-perfectionist/no-complex-template-expression': 'error',
      'vue-perfectionist/no-template-type-assertion': 'error',
      'vue-perfectionist/no-watcher-cleanup-after-await': 'error',
      'vue-perfectionist/require-props-prefix': 'error',
    },
  },
])

对于仅使用 JavaScript 的单文件组件,省略 TypeScript 解析器导入及 parserOptions.parser。如果已有 Vue 配置提供了解析器,只需添加插件和所需规则。

运行 ESLint ​

对源文件运行 ESLint,添加 --fix 可应用受支持的修复:

shell
pnpm exec eslint .
pnpm exec eslint . --fix

组合式函数的返回对象和消费端解构可以分别启用 sort-composable-return 与 sort-composable-destructure。 两者默认状态在前、方法在后,保留组内顺序,只自动修复空行。

使用 require-composable-return-bindings 要求返回字段显式暴露本地绑定。默认允许改名,对内联表达式只报告、不修复。

如果项目约定调用方可以直接解构组合式函数的返回值,可以返回包含 ref 的普通对象,并启用 no-reactive-composable-return。

使用 sort-composable-body 检查具名组合式函数体的 直接语句。它沿用 setup 排序偏好,独立于成员排序应用保守的移动修复。

使用 consistent-template-element-layout 检查块级元素的完整单行或展开布局,以及块级兄弟分行。 默认采用兼容格式化工具的仅报告模式,可显式开启结束标签安全修复和组件布局分组。

后续步骤 ​

  • 选择规则:按用途浏览规则,查看适用文件范围、默认行为和自动修复支持情况。
  • 配置:配置独立 JS/TS 文件、自动导入的 Vue API 和公共类型。
  • 规则组合:组合相关检查,了解自动修复边界及与其他插件的交互。
  • 问题排查:排查规则未生效、缺少自动修复和类型服务配置。