使用 eslint-plugin-vue 代替 vue-eslint-parser 是一个更直接的方法,因为 eslint-plugin-vue 已经包含了许多针对 Vue 文件的解析和规则定义。下面是如何使用 eslint-plugin-vue 来创建一个自定义规则,检查 .vue 文件的 <template> 块中不符合 kebab-case 和 PascalCase 的标签。

  1. 创建 ESLint 插件

    首先,创建一个新的 npm 包来包含你的 ESLint 插件:

    mkdir eslint-plugin-vue-template-case
    cd eslint-plugin-vue-template-case
    npm init -y
    
  2. 安装必要的依赖

    安装 eslinteslint-plugin-vue 作为依赖:

    npm install eslint eslint-plugin-vue
    
  3. 创建自定义规则

    在项目目录中创建一个名为 rules 的文件夹,并在其中创建一个名为 template-case.js 的文件:

    // rules/template-case.js
    function isKebabCase(tag) {
      return /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(tag);
    }
    
    function isPascalCase(tag) {
      return /^[A-Z][a-zA-Z0-9]*$/.test(tag);
    }
    
    module.exports = {
      meta: {
        type: 'suggestion',
        docs: {
          description: 'enforce kebab-case and PascalCase in <template> block',
          category: 'Stylistic Issues',
          recommended: false
        },
        fixable: null,
        schema: []
      },
      create(context) {
        return {
          VElement(node) {
            const tagName = node.rawName;
            if (!isKebabCase(tagName) && !isPascalCase(tagName)) {
              context.report({
                node,
                loc: node.loc,
                message: 'Tag "{{tagName}}" is not in kebab-case or PascalCase.',
                data: {
                  tagName
                }
              });
            }
          }
        };
      }
    };
    
  4. 导出规则

    在项目根目录中创建一个 index.js 文件来导出你的规则:

    // index.js
    module.exports = {
      rules: {
        'template-case': require('./rules/template-case')
      }
    };
    
  5. 配置 ESLint 使用自定义规则

    在你的 Vue 项目中,配置 ESLint 使用你刚创建的插件。首先,在你的 Vue 项目中安装你的插件(假设你在本地开发,可以使用 npm link):

    cd path/to/your/vue-project
    npm link path/to/eslint-plugin-vue-template-case
    

    然后,更新你的 .eslintrc.js 文件来使用这个插件和规则:

    // .eslintrc.js
    module.exports = {
      parserOptions: {
        parser: 'babel-eslint',
        sourceType: 'module'
      },
      extends: [
        'plugin:vue/recommended'
      ],
      plugins: [
        'vue-template-case'
      ],
      rules: {
        'vue-template-case/template-case': 'error'
      }
    };
    
  6. 运行 ESLint 检查

    现在,你可以在你的 Vue 项目中运行 ESLint 来检查 <template> 块中的标签是否符合 kebab-case 和 PascalCase:

    npx eslint --ext .js,.vue src
    

这个自定义 ESLint 规则会检查 .vue 文件中的 <template> 块,确保所有标签都符合 kebab-case 或 PascalCase 的命名规范。如果有不符合规范的标签,会报告错误。使用 eslint-plugin-vue 可以更方便地解析 Vue 文件并应用规则。

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3