跳到内容

ESLint

Next.js 提供了一个 ESLint 插件,eslint-plugin-next,它已经捆绑在基本配置中,可以捕获 Next.js 应用程序中的常见问题和错误。

参考

以下 ESLint 插件的推荐规则集都在 eslint-config-next 中使用

这将优先于 next.config.js 中的配置。

规则

完整的规则集如下

在推荐配置中启用规则描述
@next/next/google-font-display强制使用 Google Fonts 的 font-display 行为。
@next/next/google-font-preconnect确保 preconnect 与 Google Fonts 一起使用。
@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防止客户端组件成为异步函数。
@next/next/no-before-interactive-script-outside-document防止在 pages/_document.js 之外使用 next/scriptbeforeInteractive 策略。
@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/documentHead 组件一起使用。
@next/next/no-typos防止在 Next.js 的数据获取函数中出现常见拼写错误
@next/next/no-unwanted-polyfillio防止来自 Polyfill.io 的重复 polyfills。

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

示例

Linting 自定义目录和文件

默认情况下,Next.js 将对 pages/app/components/lib/src/ 目录中的所有文件运行 ESLint。但是,你可以使用生产构建的 next.config.jseslint 配置中的 dirs 选项来指定目录

next.config.js
module.exports = {
  eslint: {
    dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build)
  },
}

同样,--dir--file 标志可以用于 next lint 来 lint 特定目录和文件

终端
next lint --dir pages --dir utils --file bar.js

在 monorepo 中指定根目录

如果你在 Next.js 未安装在根目录中的项目(例如 monorepo)中使用 eslint-plugin-next,你可以告诉 eslint-plugin-next 在哪里找到你的 Next.js 应用程序,方法是使用 .eslintrc 中的 settings 属性

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next'],
    settings: {
      next: {
        rootDir: 'packages/my-app/',
      },
    },
  }),
]

export default eslintConfig

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

禁用缓存

为了提高性能,ESLint 处理的文件信息默认会被缓存。这存储在 .next/cache 或你定义的 构建目录中。如果你包含任何依赖于单个源文件内容之外的 ESLint 规则,并且需要禁用缓存,请将 --no-cache 标志与 next lint 一起使用。

终端
next lint --no-cache

禁用规则

如果你想修改或禁用受支持的插件(reactreact-hooksnext)提供的任何规则,你可以使用 .eslintrc 中的 rules 属性直接更改它们

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next'],
    rules: {
      'react/no-unescaped-entities': 'off',
      '@next/next/no-page-custom-font': 'off',
    },
  }),
]

export default eslintConfig

使用 Core Web Vitals

首次运行 next lint 并且选择 strict 选项时,将启用 next/core-web-vitals 规则集。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next/core-web-vitals'],
  }),
]

export default eslintConfig

如果 next/core-web-vitals 影响 Core Web Vitalsnext/core-web-vitals 会更新 eslint-plugin-next,以便对默认情况下为警告的许多规则报错。

对于使用 Create Next App 构建的新应用程序,会自动包含 next/core-web-vitals 入口点。

使用 TypeScript

除了 Next.js ESLint 规则之外,create-next-app --typescript 还会使用 next/typescript 将 TypeScript 特定的 lint 规则添加到你的配置中

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next/core-web-vitals', 'next/typescript'],
  }),
]

export default eslintConfig

这些规则基于 plugin:@typescript-eslint/recommended。 有关更多详细信息,请参阅 typescript-eslint > Configs

使用 Prettier

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

首先,安装依赖项

终端
npm install --save-dev eslint-config-prettier
 
yarn add --dev eslint-config-prettier
 
pnpm add --save-dev eslint-config-prettier
 
bun add --dev eslint-config-prettier

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

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next', 'prettier'],
  }),
]

export default eslintConfig

对暂存文件运行 lint

如果你想将 next lintlint-staged 一起使用,以便对暂存的 git 文件运行 linter,你必须将以下内容添加到项目根目录中的 .lintstagedrc.js 文件中,以便指定 --file 标志的用法。

.lintstagedrc.js
const path = require('path')
 
const buildEslintCommand = (filenames) =>
  `next lint --fix --file ${filenames
    .map((f) => path.relative(process.cwd(), f))
    .join(' --file ')}`
 
module.exports = {
  '*.{js,jsx,ts,tsx}': [buildEslintCommand],
}

在生产构建期间禁用 linting

如果你不希望 ESLint 在 next build 期间运行,你可以将 next.config.js 中的 eslint.ignoreDuringBuilds 选项设置为 true

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
}
 
export default nextConfig

迁移现有配置

如果你的应用程序中已经配置了 ESLint,我们建议直接从这个插件扩展,而不是包含 eslint-config-next,除非满足以下几个条件。

如果以下条件为真

  • 你已经安装了以下一个或多个插件(单独安装或通过不同的配置(如 airbnbreact-app)安装)
    • react
    • react-hooks
    • jsx-a11y
    • import
  • 你已定义了特定的 parserOptions,这些选项与 Next.js 中 Babel 的配置方式不同(除非你自定义了 Babel 配置,否则不建议这样做)
  • 你已安装了 eslint-plugin-import 以及 Node.js 和/或 TypeScript 解析器,用于处理导入

那么我们建议删除这些设置(如果你喜欢 eslint-config-next 中配置这些属性的方式),或者直接从 Next.js ESLint 插件扩展

module.exports = {
  extends: [
    //...
    'plugin:@next/next/recommended',
  ],
}

该插件可以正常安装在你的项目中,而无需运行 next lint

终端
npm install --save-dev @next/eslint-plugin-next
 
yarn add --dev @next/eslint-plugin-next
 
pnpm add --save-dev @next/eslint-plugin-next
 
bun add --dev @next/eslint-plugin-next

这消除了由于跨多个配置导入相同的插件或解析器而可能发生的冲突或错误的风险。

其他配置

如果你已经使用单独的 ESLint 配置并想包含 eslint-config-next,请确保它在其他配置之后最后扩展。例如

eslint.config.mjs
import js from '@eslint/js'
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
  recommendedConfig: js.configs.recommended,
})

const eslintConfig = [
  ...compat.config({
    extends: ['eslint:recommended', 'next'],
  }),
]

export default eslintConfig

next 配置已经处理了 parserpluginssettings 属性的默认值设置。除非你的用例需要不同的配置,否则无需手动重新声明任何这些属性。

如果你包含任何其他可共享的配置,你需要确保这些属性没有被覆盖或修改。 否则,我们建议删除任何与 next 配置共享行为的配置,或者如上所述直接从 Next.js ESLint 插件扩展。