Skip to main content

ESLint 插件

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

¥Next.js provides an ESLint plugin, eslint-plugin-next, already bundled within the base configuration that makes it possible to catch common issues and problems in a Next.js application.

参考

¥Reference

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

¥Recommended rule-sets from the following ESLint plugins are all used within eslint-config-next:

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

¥This will take precedence over the configuration from next.config.js.

规则

¥Rules

完整的规则如下:

¥The full set of rules is as follows:

在推荐配置中启用规则描述
@next/next/google-font-display使用 Google Fonts 强制执行字体显示行为。
@next/next/google-font-preconnect确保 preconnect 与 Google 字体一起使用。
@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由于 LCP 较慢和带宽较高,请防止使用 <img> 元素。
@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 的重复填充。

我们建议在开发过程中使用适当的 integration 直接在代码编辑器中查看警告和错误。

¥We recommend using an appropriate integration to view warnings and errors directly in your code editor during development.

示例

¥Examples

对自定义目录和文件进行 Lint 处理

¥Linting custom directories and files

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

¥By default, Next.js will run ESLint for all files in the pages/, app/, components/, lib/, and src/ directories. However, you can specify which directories using the dirs option in the eslint config in next.config.js for production builds:

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 检测:

¥Similarly, the --dir and --file flags can be used for next lint to lint specific directories and files:

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

在指定根目录中 monorepo

¥Specifying a root directory within a monorepo

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

¥If you're using eslint-plugin-next in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell eslint-plugin-next where to find your Next.js application using the settings property in your .eslintrc:

{
"extends": "next",
"settings": {
"next": {
"rootDir": "packages/my-app/"
}
}
}

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

¥rootDir can be a path (relative or absolute), a glob (i.e. "packages/*/"), or an array of paths and/or globs.

禁用缓存

¥Disabling the cache

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

¥To improve performance, information of files processed by ESLint are cached by default. This is stored in .next/cache or in your defined build directory. If you include any ESLint rules that depend on more than the contents of a single source file and need to disable the cache, use the --no-cache flag with next lint.

next lint --no-cache

禁用规则

¥Disabling rules

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

¥If you would like to modify or disable any rules provided by the supported plugins (react, react-hooks, next), you can directly change them using the rules property in your .eslintrc:

{
"extends": "next",
"rules": {
"react/no-unescaped-entities": "off",
"@next/next/no-page-custom-font": "off"
}
}

使用核心 Web 生命力

¥With Core Web Vitals

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

¥The next/core-web-vitals rule set is enabled when next lint is run for the first time and the strict option is selected.

{
"extends": "next/core-web-vitals"
}

next/core-web-vitalseslint-plugin-next 更新为在许多规则上出错,如果这些规则影响 核心网络生命力,则默认情况下会发出警告。

¥next/core-web-vitals updates eslint-plugin-next to error on a number of rules that are warnings by default if they affect Core Web Vitals.

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

¥The next/core-web-vitals entry point is automatically included for new applications built with Create Next App.

使用 TypeScript

¥With TypeScript

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

¥In addition to the Next.js ESLint rules, create-next-app --typescript will also add TypeScript-specific lint rules with next/typescript to your config:

{
"extends": ["next/core-web-vitals", "next/typescript"]
}

这些规则基于 plugin:@typescript-eslint/recommended。详细信息请参见 typescript-eslint > 配置

¥Those rules are based on plugin:@typescript-eslint/recommended. See typescript-eslint > Configs for more details.

使用 Prettier

¥With Prettier

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

¥ESLint also contains code formatting rules, which can conflict with your existing Prettier setup. We recommend including eslint-config-prettier in your ESLint config to make ESLint and Prettier work together.

首先,安装依赖:

¥First, install the dependency:

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 配置中:

¥Then, add prettier to your existing ESLint config:

{
"extends": ["next", "prettier"]
}

在暂存文件上运行 lint

¥Running lint on staged files

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

¥If you would like to use next lint with lint-staged to run the linter on staged git files, you'll have to add the following to the .lintstagedrc.js file in the root of your project in order to specify usage of the --file flag.

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

¥Disabling linting during production builds

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

¥If you do not want ESLint to run during next build, you can set the eslint.ignoreDuringBuilds option in next.config.js to true:

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
const nextConfig = {
eslint: {
// Warning: This allows production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
}

export default nextConfig

迁移现有配置

¥Migrating existing config

如果你已经在应用中配置了 ESLint,我们建议直接从此插件扩展,而不是包含 eslint-config-next,除非满足一些条件。

¥If you already have ESLint configured in your application, we recommend extending from this plugin directly instead of including eslint-config-next unless a few conditions are met.

¥Recommended plugin ruleset

如果满足以下条件:

¥If the following conditions are true:

  • 你已经安装了以下一个或多个插件(单独安装或通过不同的配置(例如 airbnbreact-app)):

    ¥You have one or more of the following plugins already installed (either separately or through a different config such as airbnb or react-app):

    • react

    • react-hooks

    • jsx-a11y

    • import

  • 你定义了与 Next.js 中 Babel 的配置方式不同的特定 parserOptions(除非你有 定制你的 Babel 配置,否则不建议这样做)

    ¥You've defined specific parserOptions that are different from how Babel is configured within Next.js (this is not recommended unless you have customized your Babel configuration)

  • 你安装了 eslint-plugin-import,并定义了 Node.js 和/或 TypeScript resolvers 来处理导入

    ¥You have eslint-plugin-import installed with Node.js and/or TypeScript resolvers defined to handle imports

然后,如果你更喜欢在 eslint-config-next 中配置这些属性,我们建议你删除这些设置,或者直接从 Next.js ESLint 插件扩展:

¥Then we recommend either removing these settings if you prefer how these properties have been configured within eslint-config-next or extending directly from the Next.js ESLint plugin instead:

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

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

¥The plugin can be installed normally in your project without needing to run 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

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

¥This eliminates the risk of collisions or errors that can occur due to importing the same plugin or parser across multiple configurations.

其他配置

¥Additional configurations

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

¥If you already use a separate ESLint configuration and want to include eslint-config-next, ensure that it is extended last after other configurations. For example:

{
"extends": ["eslint:recommended", "next"]
}

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

¥The next configuration already handles setting default values for the parser, plugins and settings properties. There is no need to manually re-declare any of these properties unless you need a different configuration for your use case.

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

¥If you include any other shareable configurations, you will need to make sure that these properties are not overwritten or modified. Otherwise, we recommend removing any configurations that share behavior with the next configuration or extending directly from the Next.js ESLint plugin as mentioned above.