Nuxt.js项目中ESLint的特殊配置需求

解读

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

  1. 你是否真的把 Nuxt 当成“SSR + 自动文件系统路由 + 同构”的框架,而不是“又一个 Vue 项目”;
  2. 你是否知道 Nuxt 的代码边界(pages、plugins、server、composables、nuxt.config)各自跑在什么运行时,从而该用哪套全局变量、解析器、插件;
  3. 你是否能把规则、解析器、插件、ignore、性能、CI 五件事一次说清,并给出可落地的国内工程化样板(pnpm monorepo + Husky + lint-staged + GitHub Actions)。
    答得太浅(“装个 @nuxtjs/eslint-config 就行”)会被追问细节;答得太偏(“自己写 parser 文件”)会被质疑成本。要把“官方生态 + 国内落地差异”同时摆出来。

知识点

  1. 运行时差异
    • 客户端代码运行在浏览器,全局变量是 window、document。
    • 服务端代码运行在 Node,全局变量是 global、process、__dirname。
    • 同构代码(plugins、composables、middleware)两边都会执行,必须同时识别两种全局变量。
  2. 文件系统路由约定
    • pages 目录下的 .vue 文件会自动变成路由,变量未使用不能粗暴报 no-unused-vars。
    • layouts、plugins、server/api、composables 目录也有各自“潜规则”导出。
  3. 解析器与插件
    • vue-eslint-parser 必须放在第一位,让 ESLint 先解析 .vue 的 <template> 和 <script>。
    • @typescript-eslint/parser 负责 <script lang="ts"> 块;@typescript-eslint/eslint-plugin 提供 TypeScript 规则。
    • eslint-plugin-nuxt 补充 Nuxt 专用规则(no-env-in-pages、no-globals-in-ssr 等)。
  4. 共享配置层级
    • @nuxtjs/eslint-config(JS 项目)
    • @nuxtjs/eslint-config-typescript(TS 项目,已内置 vue-parser 与 ts-parser)
    • 国内团队一般再包一层 @company/eslint-config-nuxt,把 prettier、sonarjs、security 规则合并进去,用 pnpm 的 workspace:* 协议锁定版本。
  5. 性能与 CI
    • Nuxt 3 默认启用 .eslintcache,但 GitHub Actions 里要手动把 ~/.eslintcache 加到 actions/cache,否则每次冷启动 3 min+。
    • lint-staged 只校验 git diff,配合 —max-warnings=0 阻断提交;MR 阶段再跑一次全量 scan,防止跨文件依赖问题。
  6. 国内常见坑
    • Windows 开发者路径大小写不敏感,eslint-plugin-import 的 case-sensitive 规则要在 CI 里强制开启。
    • 阿里/腾讯私有 npm 源同步滞后,需把 @nuxtjs/eslint-config-typescript 锁在 12.0.0 以上,否则 vue-parser 版本冲突。

答案

“要在 Nuxt 项目里把 ESLint 配到‘团队开箱即用’,我会分四步:
第一步,选型。Nuxt 3 全 TypeScript,我直接装 @nuxtjs/eslint-config-typescript,它已经内置 vue-eslint-parser 和 @typescript-eslint/parser,省掉自己拼 parser 的坑。
第二步,在项目根写 .eslintrc.js,只留三行:
root: true,
extends: ['@nuxtjs/eslint-config-typescript'],
rules: { /* 业务微调 */ }
这样 pages、plugins、server、composables 目录都会被自动覆盖。
第三步,处理双端全局变量。在 overrides 里加两段:

  • files: ['server/**/*', 'nuxt.config.ts'], env: { node: true }
  • files: ['pages//*', 'layouts//*'], env: { browser: true }
    同构代码默认同时开启 node:true 和 browser:true,保证 plugins/composables 不报 no-undef。
    第四步,性能与流程。
  • 在 package.json 里把 lint 脚本写成 eslint . --cache --cache-location ./node_modules/.cache/eslint,配合 lint-staged 只扫 git diff,平均 2 秒完成提交检查。
  • CI 阶段用 GitHub Actions,把 ~/.eslintcache 和 node_modules 一起缓存,全量扫描 30 秒以内;同时加 —max-warnings=0,红线阻断。
  • 最后包一层 @company/eslint-config-nuxt,把 prettier、sonarjs、security 统一打进去,版本用 pnpm workspace:* 锁死,国内私有源再慢也不会出现 parser 冲突。”

拓展思考

  1. 微前端场景:Nuxt 仅作为子应用,ESLint 需要把主应用的 global 变量(如 qiankun 的 POWERED_BY_QIANKUN)加到 globals 白名单,否则报 no-undef。
  2. 渐进迁移:老项目从 Nuxt 2 升 3,JavaScript 与 TypeScript 并存,可在 overrides 里对 .js 文件降级用 @babel/eslint-parser,保证迁移期规则不撕裂。
  3. 自定义规则:如果团队采用“pages 目录下必须导出 definePageMeta”的约定,可写 eslint-plugin-local,利用 vue-eslint-parser 的 AST 拿到 ExportDefaultDeclaration,自定义 nuxt/require-page-meta 规则,一键扫码修正。