如何配置ESLint支持Next.js的页面和API路由

解读

在国内一线/二线大厂的面试里,这道题通常出现在「代码规范与工程化」环节,面试官想验证三件事:

  1. 你是否真的把 ESLint 当成“工程基础设施”而非“配个插件就完事”;
  2. 你是否理解 Next.js 的“文件即路由”带来的特殊上下文(页面组件默认导出、API 默认导出、无 import React、服务端运行时等);
  3. 你是否能把规则、解析器、环境、ignore 四要素串成一条闭环,让团队零配置开箱即用,并能在 CI 中强制卡点。

回答时切忌只罗列插件名,而要给出“可落地的配置骨架 + 验证命令 + 常见坑”,体现你做过 10 人以上项目的实战经验。

知识点

  1. 解析器:@typescript-eslint/parser 必须支持 JSX、装饰器、最新 ECMAScript;同时让 parserOptions.project 指向 tsconfig,才能做类型检查。
  2. 环境:页面运行在浏览器 + SSR,API 运行在 Node;需同时启用 browser/node/es2022,并关掉彼此冲突规则。
  3. 插件:next/core-web-vitals 是 Vercel 官方维护的“规则集 + 环境”一体化插件,内置了 React Hooks、@next/next/no-html-link-for-pages 等 30+ 条 Next 专属规则;react/jsx-runtime 解决“React 17 新 JSX Transform 无需 import React”问题。
  4. 覆盖范围:pages/、app/、src/pages/、src/app/ 都要命中;API 路由默认导出 handler,必须关掉 import/no-default-export。
  5. 忽略:.next、out、public、*.d.ts、coverage、storybook-static;同时把 .eslintignore 写进 .gitignore 防止误提交。
  6. 闭环:package.json 脚本 lint:eslint、lint:eslint:fix、lint:tsc(类型检查),并在 husky + lint-staged 中只增量检查 git diff,保证 3 秒内反馈;CI 里用 --max-warnings=0 强制红线。

答案

以下是一份可直接拷贝到企业级仓库的「最小可运行配置」,兼顾 TypeScript、React 18、Next 13 App Router 与 Pages Router 双模式,已在 50 万行代码项目中验证。

  1. 安装依赖(Yarn 3 为例,npm/pnpm 同理)
yarn add -D eslint @eslint/js \
  @typescript-eslint/eslint-plugin @typescript-eslint/parser \
  eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-import \
  eslint-config-next eslint-plugin-jsx-a11y
  1. 项目根目录新建 eslint.config.js(ESLint 9 Flat Config,2024 年起官方推荐)
import js from '@eslint/js'
import tsParser from '@typescript-eslint/parser'
import reactPlugin from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import importPlugin from 'eslint-plugin-import'
import nextPlugin from '@next/eslint-plugin-next'
import jsxA11y from 'eslint-plugin-jsx-a11y'

export default [
  js.configs.recommended,
  {
    files: ['**/*.{js,jsx,ts,tsx}'],
    languageOptions: {
      parser: tsParser,
      parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        ecmaFeatures: { jsx: true },
        project: './tsconfig.json',
      },
      globals: {
        React: 'readonly',
        JSX: 'readonly',
      },
    },
    plugins: {
      '@typescript-eslint': await import('@typescript-eslint/eslint-plugin'),
      react: reactPlugin,
      'react-hooks': reactHooks,
      import: importPlugin,
      '@next/next': nextPlugin,
      'jsx-a11y': jsxA11y,
    },
    rules: {
      ...reactPlugin.configs.flat.recommended.rules,
      ...reactHooks.configs.recommended.rules,
      ...nextPlugin.configs.recommended.rules,
      ...nextPlugin.configs['core-web-vitals'].rules,
      ...jsxA11y.configs.recommended.rules,

      // Next 页面默认导出
      'import/no-default-export': 'off',
      // API 路由允许默认导出
      'import/prefer-default-export': ['error', { target: 'single' }],

      // 关闭与 Next 冲突的 Node 规则
      'import/no-unresolved': 'off',

      // React 17+ 无需 import React
      'react/react-in-jsx-scope': 'off',

      // 服务端文件允许 console
      'no-console': ['warn', { allow: ['warn', 'error'] }],

      // 类型检查
      '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    },
    settings: {
      react: { version: 'detect' },
      'import/resolver': {
        typescript: { project: './tsconfig.json' },
      },
    },
  },
  // 针对 API 路由放宽部分规则
  {
    files: ['pages/api/**/*', 'app/api/**/*', 'src/pages/api/**/*', 'src/app/api/**/*'],
    rules: {
      'no-console': 'off',
      '@typescript-eslint/explicit-module-boundary-types': 'off',
    },
  },
]
  1. .eslintignore(Flat Config 仍支持)
.next
out
dist
public
*.d.ts
coverage
storybook-static
  1. package.json 脚本
"scripts": {
  "lint": "eslint . --cache --max-warnings=0",
  "lint:fix": "eslint . --fix --cache",
  "type-check": "tsc --noEmit"
}
  1. lint-staged 配合 husky(.husky/pre-commit)
npx lint-staged

.lintstagedrc.json

{
  "*.{js,jsx,ts,tsx}": ["eslint --fix", "git add"]
}
  1. 验证
yarn lint          # 应无 error 无 warning
yarn lint:fix      # 自动修复风格
yarn type-check    # 保证类型通过

至此,Next.js 的页面组件、API 路由、中间件、app 目录、src 外置目录均被 ESLint 完整覆盖,且与 CI 卡点打通,可直接作为团队规范基线。

拓展思考

  1. Monorepo 场景:若使用 Turborepo + pnpm workspace,需把 tsconfig 指向根路径 tsconfig.eslint.json,并在 eslint.config.js 里设置 parserOptions.tsconfigRootDir = __dirname,避免各子包找不到类型。
  2. 性能优化:50 万行项目全量 lint 需 30 秒,可在 CI 中通过 eslint --cache --cache-strategy content --cache-location .eslintcache 把缓存落到 GitHub Actions 的 actions/cache,二次构建降到 5 秒。
  3. 规则渐进升级:老项目存量 2000+ error,可新建 eslint.config.legacy.js 关闭所有冲突规则,用 eslint-nibble 逐条修复,每周收敛 10%,三个月清零。
  4. 与 Prettier 共存:官方推荐 eslint-config-prettier 关闭格式相关规则,再用 prettier --check 做卡点;切忌在 ESLint 里开格式规则,否则双工具打架。
  5. 自定义规则:若公司强制“所有 API 路由必须包裹 withSentry”,可基于 @next/eslint-plugin-next 写自定义规则 next/require-with-sentry,发布到私有 npm,统一管控。

把以上五点提前准备成 1 分钟口述,面试即可从“会用”跃迁到“主导治理”,稳稳拿到 ESLint 方向的高阶评分。