如何配置规则支持Vue 3的Composition API

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否真的在 Vue 3 项目里落地过 ESLint,而不是“跑通 demo”就算;
  2. 是否理解 Composition API 带来的新语法(<script setup>、顶层的 import { ref }、宏 defineProps 等)对静态分析带来的挑战;
  3. 能否把规则、插件、解析器、共享配置四个维度串成“可复制的工程方案”,而不是零散地贴几行配置。

国内真实场景里,Vue 3 项目普遍用 Vite + TypeScript + <script setup>,CI 端用 GitLab-CI 或 GitHub Actions,面试官希望听到“从 npm 安装到最终 eslint --max-warnings=0 在流水线里卡住红线”的完整闭环。

知识点

  1. 解析器链:
    @typescript-eslint/parser → 负责 TS 语法;
    vue-eslint-parser → 负责 .vue 单文件,把 <template>、<script>、<script setup> 拆成 AST 片段,再丢给 TS 解析器。

  2. 插件集:
    eslint-plugin-vue:Vue 官方规则,区分 Vue3/Composition 与 Vue2/Options 两套环境;
    @typescript-eslint/eslint-plugin:TS 规则,避免 no-undef 误报类型声明;
    eslint-plugin-prettier(可选):国内团队普遍把 Prettier 集成到 ESLint 一条命令,减少冲突。

  3. 共享配置:
    plugin:vue/vue3-recommended 已经包含 Composition API 相关规则;
    若需自定义,可继承后 rules 覆盖,如关闭 vue/require-default-prop(Composition API 不再强制 props default)。

  4. 全局变量与宏:
    defineProps、defineEmits、defineExpose 等由 vue-eslint-parser 自动注入全局,无需手动 globals,但必须保证 parser 的 ecmaVersion>=2022,否则解析失败。

  5. 文件覆盖策略:
    国内项目常见“TS 文件走 TS 规则,Vue 文件走 Vue+TS 规则”,用 overrides 数组隔离,避免 *.ts 被 vue-eslint-parser 误伤性能。

  6. 流水线卡点:
    国内 GitLab-CI 模板:

    lint:
      stage: check
      script:
        - npm ci
        - npm run lint:eslint
      only:
        - merge_requests
    

    配合 eslint --max-warnings=0 确保 MR 红线。

答案

  1. 安装依赖(一次性锁定版本,避免 CI 漂移):

    npm i -D eslint@^8 vue-eslint-parser@^9 eslint-plugin-vue@^9 \
              @typescript-eslint/parser@^6 @typescript-eslint/eslint-plugin@^6 \
              typescript@^5
    
  2. 在项目根新建 .eslintrc.js,采用 CommonJS 导出,兼容国内大多数 Node 镜像源缓存:

    module.exports = {
      root: true,
      // 1. 解析器链:vue-eslint-parser 优先,再把 <script> 内容交给 TS 解析器
      parser: 'vue-eslint-parser',
      parserOptions: {
        parser: '@typescript-eslint/parser',
        ecmaVersion: 2022,
        sourceType: 'module',
        project: './tsconfig.json', // 开启类型检查规则
        extraFileExtensions: ['.vue'],
      },
      env: {
        browser: true,
        node: true,
        es2022: true,
      },
      // 2. 插件
      plugins: ['vue', '@typescript-eslint'],
      extends: [
        'eslint:recommended',
        '@typescript-eslint/recommended',
        'plugin:vue/vue3-recommended', // 关键:Vue3 + Composition API 规则集
      ],
      rules: {
        // 3. 国内团队常见微调
        'vue/multi-word-component-names': 'off', // 允许 index.vue
        '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
        // 关闭与 Prettier 冲突的规则
        'vue/html-self-closing': ['error', { html: { void: 'always' } }],
      },
      // 4. 文件级覆盖
      overrides: [
        {
          files: ['*.ts', '*.tsx'],
          parser: '@typescript-eslint/parser',
          extends: ['@typescript-eslint/recommended'],
          rules: {
            'vue/comment-directive': 'off', // 纯 TS 文件无需 Vue 规则
          },
        },
        {
          files: ['*.vue'],
          rules: {
            // 允许 <script setup> 顶层 await
            'vue/no-setup-props-destructure': 'off',
          },
        },
      ],
    };
    
  3. 在 package.json 给出统一命令,避免开发者本地与 CI 不一致:

    "scripts": {
      "lint:eslint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --max-warnings=0 --cache --cache-location node_modules/.cache/eslint"
    }
    
  4. VS Code 集成(国内镜像加速):
    安装官方扩展 dbaeumer.vscode-eslint,在工作区 .vscode/settings.json 中追加:

    {
      "eslint.validate": ["javascript", "typescript", "vue"],
      "eslint.codeAction.showDocumentation": { "enable": true }
    }
    

    保存即自动修复,减少 code review 噪音。

  5. Git Hooks(husky + lint-staged,国内源):

    npx husky-init && npm i -D lint-staged@^13
    

    在 .husky/pre-commit 写入:

    npx lint-staged
    

    package.json 补充:

    "lint-staged": {
      "*.{vue,js,ts,jsx,tsx}": ["npm run lint:eslint -- --fix", "git add"]
    }
    

    保证 Composition API 代码在 commit 前强制修复。

拓展思考

  1. 大型 monorepo 下,如何给每个子包单独指定 tsconfig.eslint.json,避免交叉引用导致类型检查 OOM?
    思路:在 parserOptions.project 指向子包内专用 tsconfig,配合 tsconfig.eslint.json 只包含待检文件,CI 里用 lerna/nx 并行跑,时间从 5 min 降到 40 s。

  2. 当团队决定“全量 <script setup>”时,如何自定义 ESLint 规则强制禁用 Options API?
    可写内部插件 eslint-plugin-no-options-api,利用 vue-eslint-parser 的 AST 访问 ExportDefaultDeclaration > ObjectExpression,若包含 data、methods 字段即报错,从源头杜绝混合写法。

  3. 如何与 Vue 3.3+ 的“泛型组件”语法 <script setup lang="ts" generic="T extends string"> 共存?
    需要 vue-eslint-parser@9.3+ 与 @typescript-eslint/parser@6+ 才识别 generic 属性,老版本会直接解析失败;CI 镜像源需同步升级,否则会出现“莫名其妙红线”。

  4. 国内网络下,CI 缓存 node_modules/.cache/eslint 与 .eslintcache 的策略差异:
    若用 GitHub Actions 自建缓存键 eslint-${{ hashFiles('package-lock.json') }},可让 10 万行代码项目缓存命中率 95%,MR 检查时间从 3 min 降到 20 s;但 GitLab-CI 需手动 cache: paths: [node_modules/.cache/eslint],否则每次重新解析 AST,导致流水线超时。

  5. 未来 Vue 3.4 可能引入 defineModel 宏,ESLint 规则如何提前适配?
    关注 eslint-plugin-vue 的下一版本里程碑,提前在 globals 注入 defineModel,并在公司私有配置里先行开启实验规则,保证升级当天零红线。