Skip to content

为 Vue 中的 Pug 模板提供的 ESLint 支持

让你的 vue/* rules 直接在 <template lang="pug"> 上运行,用 eslint --fix 格式化 Pug,并保证模板完好无损:每个修复在应用之前都会经过检查。

sh
npm i -D eslint-plugin-pug-vue
UserCard.vue
<template lang="pug">div.card(·class="shadow"·,·:title·=·"title"·)····h2(·v-if='title'·)·{{·title·}}····input(v-model="name"·,·type='text'·disabled)/</template>
15 个问题将鼠标悬停在波浪线上可查看警告。
ESLint 报告的全部 15 条警告
  • 2:1 Omit `div` before a class or id shorthand vue-pug/implicit-div
  • 2:10 Unexpected space after '(' vue-pug/attribute-parens-spacing
  • 2:11 Use the '.shadow' shorthand instead of the class attribute vue-pug/prefer-shorthand
  • 2:26 Unexpected comma in attribute block vue-pug/attribute-commas
  • 2:34 Unexpected space around '=' vue-pug/attribute-equals-spacing
  • 2:36 Unexpected space around '=' vue-pug/attribute-equals-spacing
  • 2:44 Unexpected space before ')' vue-pug/attribute-parens-spacing
  • 3:1 Expected indentation of 2 spaces but found 4 spaces vue-pug/indent
  • 3:8 Unexpected space after '(' vue-pug/attribute-parens-spacing
  • 3:14 Expected double quotes vue-pug/attribute-quotes
  • 3:21 Unexpected space before ')' vue-pug/attribute-parens-spacing
  • 4:1 Expected indentation of 2 spaces but found 4 spaces vue-pug/indent
  • 4:26 Unexpected comma in attribute block vue-pug/attribute-commas
  • 4:33 Expected double quotes vue-pug/attribute-quotes
  • 4:49 Unexpected self-closing `/` vue-pug/self-closing

你的 vue/* rules,直接用在 Pug 上 ​

eslint-plugin-vue 的 rules 以原有的名称和选项在 Pug 模板上运行:缺失的 key、 未使用的变量、属性顺序、已弃用的语法。少数无法在 Pug 上工作的 rules 会被 关闭,或只在 Pug 模板内部被屏蔽,因此它们仍会继续检查你的 HTML 模板。

哪些 rules 会在 Pug 上运行

vue
<template lang="pug">
ul
  li(v-for="todo in todos") {{ todo.title }}
</template>
txt
3:3  error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key

用 eslint --fix 格式化 ​

十二条小巧的 vue-pug/* rules 负责格式化 Pug 本身:缩进、属性块的间距、逗号、引号 和换行,以及 .class / #id 简写。每条 rule 都有选项, 也都可以关闭。不需要 Prettier,也不会有第二个格式化工具在保存时和 ESLint 打架。

查看所有规则

js
// eslint.config.js
import pluginVue from 'eslint-plugin-vue'
import vuePug from 'eslint-plugin-pug-vue'

export default [
  ...pluginVue.configs['flat/recommended'],
  ...vuePug.configs.recommended,
]

不会破坏模板的修复 ​

在 Pug 中,缩进就是结构:移动一行,树就会改变。所以在 ESLint 把修复写入 Pug 模板之前, 插件会先检查它,无论这个修复来自哪条 rule:

  1. 它会解析应用了该修复之后的模板;
  2. 它会把标签、嵌套关系、class、属性和每一个 JavaScript 表达式与原文比较;
  3. 只有在没有任何变化时才应用修复。否则它会丢弃该修复并保留警告,让你手动修复那一行。

fix guard 如何工作

pug
//- the same template to the guard
p(class="intro lead") Hello
p.intro.lead Hello

//- a different one: a class is gone
p.intro Hello

因此 vue-pug/prefer-shorthand 可以把第一行改写成第二行,但丢失 class,或把某一行移到另一个父级下的修复,永远不会被应用。

两分钟上手 ​

它需要使用 flat config 的 ESLint 9.15 或 10、eslint-plugin-vue 10 和 vue-eslint-parser 10。 快速开始会带你完成安装、配置,以及在 VS Code 中设置保存时修复。 从 eslint-plugin-vue-pug 迁移过来?请阅读迁移指南。

基于 MIT 许可证发布。