NNext.js 中文网 GitHub

ESLint

默认情况下,Next.js 会在构建期间报告 ESLint 错误和警告。在此了解如何选择退出此行为。

Next.js 提供了一个 ESLint 配置包 eslint-config-next,可帮助你轻松发现应用中的常见问题。它包含 @next/eslint-plugin-next 插件,以及来自 eslint-plugin-react 和 eslint-plugin-react-hooks 的推荐规则集。

该包提供两个主要配置:

  • eslint-config-next:基础配置,包含 Next.js、React 和 React Hooks 规则。支持 JavaScript 和 TypeScript 文件。
  • eslint-config-next/core-web-vitals:包含基础配置的所有内容,并将影响 Core Web Vitals 的规则从警告升级为错误。推荐大多数项目使用。

此外,对于 TypeScript 项目:

  • eslint-config-next/typescript:添加来自 typescript-eslint 的 TypeScript 专用 lint 规则。可与基础配置或 core-web-vitals 配置一起使用。

设置 ESLint#

使用 ESLint CLI(扁平配置)快速启用 lint:

  1. 安装 ESLint 和 Next.js 配置:

``bash package="pnpm" pnpm add -D eslint eslint-config-next ``

``bash package="npm" npm i -D eslint eslint-config-next ``

``bash package="yarn" yarn add --dev eslint eslint-config-next ``

``bash package="bun" bun add -d eslint eslint-config-next ``

  1. 使用 Next.js 配置创建 eslint.config.mjs:

```js filename="eslint.config.mjs" import { defineConfig, globalIgnores } from 'eslint/config' import nextVitals from 'eslint-config-next/core-web-vitals'

const eslintConfig = defineConfig([

 ...nextVitals,
 // 覆盖 eslint-config-next 的默认忽略项。
 globalIgnores([
   // eslint-config-next 的默认忽略项:
   '.next/**',
   'out/**',
   'build/**',
   'next-env.d.ts',
 ]),

])

export default eslintConfig ```

  1. 运行 ESLint:

``bash package="pnpm" pnpm exec eslint . ``

``bash package="npm" npx eslint . ``

``bash package="yarn" yarn eslint . ``

``bash package="bun" bunx eslint . ``

小知识:

  • eslint-config-next 支持 ESLint 9 和 ESLint 10。ESLint 10 需要 Node.js ^20.19.0、^22.13.0 或 >=24。
  • 从 eslint-config-next@16.4.0 开始,默认的 React 版本检测支持 ESLint 10。你可以移除为规避 context.getFilename 错误而添加的 settings.react.version 覆盖项。
  • eslint-config-next 中包含的一些插件尚未在其 peer dependencies 中列出 ESLint 10,因此包管理器可能会显示 peer dependency 警告,或在启用严格 peer dependencies 时失败。

参考#

eslint-config-next 包包含以下 ESLint 插件的 recommended 规则集:

规则#

@next/eslint-plugin-next 包含的规则如下:

在 recommended 配置中启用规则描述
✓@next/next/google-font-display强制 Google Fonts 使用 font-display 行为。
✓@next/next/google-font-preconnect确保 Google Fonts 使用 preconnect。
✓@next/next/inline-script-id强制包含内联内容的 next/script 组件使用 id 属性。
✓@next/next/next-script-for-ga为 Google Analytics 使用内联脚本时,优先使用 next/script 组件。
✓@next/next/no-assign-module-variable禁止对 module 变量赋值。
✓@next/next/no-async-client-component禁止 Client Component 为异步函数。
✓@next/next/no-before-interactive-script-outside-document禁止在 pages/_document.js 之外使用 next/script 的 beforeInteractive 策略。
✓@next/next/no-css-tags禁止手动添加样式表标签。
✓@next/next/no-document-import-in-page禁止在 pages/_document.js 之外导入 next/document。
✓@next/next/no-duplicate-head禁止在 pages/_document.js 中重复使用 <Head>。
✓@next/next/no-head-element禁止使用 <head> 元素。
✓@next/next/no-head-import-in-document禁止在 pages/_document.js 中使用 next/head。
✓@next/next/no-html-link-for-pages禁止使用 <a> 元素导航到 Next.js 内部页面。
✓@next/next/no-img-element禁止使用 <img> 元素,因为 LCP 更慢且带宽更高。
✓@next/next/no-page-custom-font禁止仅在页面中使用自定义字体。
✓@next/next/no-script-component-in-head禁止在 next/head 组件中使用 next/script。
✓@next/next/no-styled-jsx-in-document禁止在 pages/_document.js 中使用 styled-jsx。
✓@next/next/no-sync-scripts禁止同步脚本。
✓@next/next/no-title-in-document-head禁止将 <title> 与 next/document 的 Head 组件一起使用。
✓@next/next/no-typos防止 Next.js 数据获取函数中的常见拼写错误
✓@next/next/no-unwanted-polyfillio防止来自 Polyfill.io 的重复 polyfill。

我们建议使用合适的集成工具,以便在开发过程中直接在代码编辑器中查看警告和错误。

<details> <summary>移除 next lint</summary>

从 Next.js 16 开始,next lint 已被移除。

作为移除的一部分,Next 配置文件中的 eslint 选项不再需要,可以安全移除。

</details>

示例#

在 monorepo 中指定根目录#

如果你在 Next.js 未安装在根目录的项目(例如 monorepo)中使用 @next/eslint-plugin-next,可以通过 eslint.config.mjs 中的 settings 属性告诉 @next/eslint-plugin-next 在哪里找到你的 Next.js 应用:

eslint.config.mjs
import { defineConfig } from 'eslint/config'
import eslintNextPlugin from '@next/eslint-plugin-next'

const eslintConfig = defineConfig([
  {
    files: ['**/*.{js,jsx,ts,tsx}'],
    plugins: {
      '@next/next': eslintNextPlugin,
    },
    settings: {
      next: {
        rootDir: 'packages/my-app/',
      },
    },
  },
])

export default eslintConfig

rootDir 可以是路径(相对或绝对)、glob(例如 "packages/*/"),或路径和/或 glob 组成的数组。

禁用规则#

如果你想修改或禁用受支持插件(react、react-hooks、next)提供的任何规则,可以直接在 eslint.config.mjs 中使用 rules 属性进行更改:

eslint.config.mjs
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'

const eslintConfig = defineConfig([
  ...nextVitals,
  {
    rules: {
      'react/no-unescaped-entities': 'off',
      '@next/next/no-page-custom-font': 'off',
    },
  },
  // 覆盖 eslint-config-next 的默认忽略项。
  globalIgnores([
    // eslint-config-next 的默认忽略项:
    '.next/**',
    'out/**',
    'build/**',
    'next-env.d.ts',
  ]),
])

export default eslintConfig

使用 Core Web Vitals#

在 ESLint 配置中启用 eslint-config-next/core-web-vitals 配置。

eslint.config.mjs
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'

const eslintConfig = defineConfig([
  ...nextVitals,
  // 覆盖 eslint-config-next 的默认忽略项。
  globalIgnores([
    // eslint-config-next 的默认忽略项:
    '.next/**',
    'out/**',
    'build/**',
    'next-env.d.ts',
  ]),
])

export default eslintConfig

eslint-config-next/core-web-vitals 会将 @next/eslint-plugin-next 中的某些 lint 规则从警告升级为错误,以帮助改善你的 Core Web Vitals 指标。

使用 Create Next App 构建的新应用会自动包含 eslint-config-next/core-web-vitals 配置。

使用 TypeScript#

除了 Next.js ESLint 规则外,create-next-app --typescript 还会通过 eslint-config-next/typescript 将 TypeScript 专用的 lint 规则添加到你的配置中:

eslint.config.mjs
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'
import nextTs from 'eslint-config-next/typescript'

const eslintConfig = defineConfig([
  ...nextVitals,
  ...nextTs,
  // 覆盖 eslint-config-next 的默认忽略项。
  globalIgnores([
    // eslint-config-next 的默认忽略项:
    '.next/**',
    'out/**',
    'build/**',
    'next-env.d.ts',
  ]),
])

export default eslintConfig

这些规则基于 plugin:@typescript-eslint/recommended。 更多详情请参阅 typescript-eslint > Configs。

使用 TypeScript 7#

使用 TypeScript 7 时,eslint-config-next 仍需要 TypeScript 6 编译器 API 供 typescript-eslint 使用。直接安装 TypeScript 7 作为 typescript 会导致 ESLint 配置加载失败。

使用 npm 时,请在 package.json 中使用这些别名,然后运行 npm install:

package.json
{
  "devDependencies": {
    "@typescript/native": "npm:typescript@7.0.2",
    "typescript": "npm:@typescript/typescript6@6.0.2"
  }
}

这为 lint 工具提供了 TypeScript 6 API,同时 tsc 运行 TypeScript 7。tsc6 命令运行 TypeScript 6。

有关原生 TypeScript 7 支持,请参阅 Microsoft 的并行安装说明和 typescript-eslint 跟踪问题。

使用 Prettier#

ESLint 还包含代码格式化规则,这可能与你现有的 Prettier 配置冲突。我们建议在 ESLint 配置中加入 eslint-config-prettier,使 ESLint 和 Prettier 协同工作。

首先,安装依赖:

bash · pnpm
pnpm add -D eslint-config-prettier
bash · npm
npm i -D eslint-config-prettier
bash · yarn
yarn add --dev eslint-config-prettier
bash · bun
bun add -d eslint-config-prettier

然后,将 prettier 添加到你现有的 ESLint 配置中:

eslint.config.mjs
import { defineConfig, globalIgnores } from 'eslint/config'
import nextVitals from 'eslint-config-next/core-web-vitals'
import prettier from 'eslint-config-prettier/flat'

const eslintConfig = defineConfig([
  ...nextVitals,
  prettier,
  // 覆盖 eslint-config-next 的默认忽略项。
  globalIgnores([
    // eslint-config-next 的默认忽略项:
    '.next/**',
    'out/**',
    'build/**',
    'next-env.d.ts',
  ]),
])

export default eslintConfig

对暂存文件运行 lint#

如果你想将 ESLint 与 lint-staged 结合使用,对暂存的 git 文件运行 linter,请将以下内容添加到项目根目录的 .lintstagedrc.js 文件中:

.lintstagedrc.js
const path = require('path')

const buildEslintCommand = (filenames) =>
  `eslint --fix ${filenames
    .map((f) => `"${path.relative(process.cwd(), f)}"`)
    .join(' ')}`

module.exports = {
  '*.{js,jsx,ts,tsx}': [buildEslintCommand],
}

迁移现有配置#

如果你的应用已经配置了 ESLint,根据你的设置,有两种方法可集成 Next.js lint 规则。

直接使用插件#

如果你已经配置了以下任一项,请直接使用 @next/eslint-plugin-next:

  • 单独安装或通过其他配置(如 airbnb 或 react-app)安装的冲突插件:
    • react
    • react-hooks
    • jsx-a11y
    • import
  • 与 Next.js 默认值不同的自定义 parserOptions(仅当你已自定义 Babel 配置时)
  • 带有自定义 Node.js 和/或 TypeScript 解析器(resolvers)的 eslint-plugin-import

在这些情况下,请直接使用 @next/eslint-plugin-next 以避免冲突:

首先,安装插件:

bash · pnpm
pnpm add -D @next/eslint-plugin-next
bash · npm
npm i -D @next/eslint-plugin-next
bash · yarn
yarn add --dev @next/eslint-plugin-next
bash · bun
bun add -d @next/eslint-plugin-next

然后将其添加到你的 ESLint 配置中:

eslint.config.mjs
import { defineConfig } from 'eslint/config'
import nextPlugin from '@next/eslint-plugin-next'

const eslintConfig = defineConfig([
  // 你的其他配置...
  {
    files: ['**/*.{js,jsx,ts,tsx}'],
    plugins: {
      '@next/next': nextPlugin,
    },
    rules: {
      ...nextPlugin.configs.recommended.rules,
    },
  },
])

export default eslintConfig

此方法消除了在多个配置中导入相同插件或解析器时可能发生的冲突或错误风险。

添加到现有配置#

如果你要在现有 ESLint 设置中添加 Next.js,请将 Next.js 配置展开到你的数组中:

eslint.config.mjs
import nextConfig from 'eslint-config-next/core-web-vitals'
// 你的其他配置导入...

const eslintConfig = [
  // 你的其他配置...
  ...nextConfig,
]

export default eslintConfig

展开 ...nextConfig 时,你添加的是多个配置对象,其中包含文件模式、插件、规则、忽略项和解析器设置。ESLint 按顺序应用配置,因此对于匹配的文件,后面的规则可以覆盖前面的规则。

小知识: 此方法适用于简单的配置。如果你的现有配置较为复杂,包含特定文件模式或相互冲突的插件配置,请考虑直接使用插件(如上所示)以获得更细粒度的控制。

版本变更
v16.4.0eslint-config-next 增加了对 ESLint 10 的兼容性,包括支持默认的 React 版本检测。
v16.0.0next lint 和 next.config.js 中的 eslint 选项已移除,改用 ESLint CLI。可使用 codemod 帮助你迁移。
Next.js 中文网