eslint

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ESLint Best Practices

ESLint 最佳实践

Provides guidance for configuring ESLint using the modern flat config format (
eslint.config.js
), selecting and tuning rules, managing plugins, and integrating linting into CI/CD workflows.
本文提供使用现代扁平配置格式(
eslint.config.js
)配置ESLint、选择和调整规则、管理插件,以及将代码检查集成到CI/CD工作流中的指导。

Core Concepts

核心概念

  • Flat config (
    eslint.config.js
    ) is the current standard. The legacy
    .eslintrc.*
    format is deprecated as of ESLint v9.
  • Configuration objects are merged in order — later objects override earlier ones for the same rule.
  • Rule severities:
    "off"
    (0) |
    "warn"
    (1) |
    "error"
    (2).
  • Plugins extend ESLint with additional rules, processors, and languages. Reference as
    pluginName/ruleName
    .
  • Flat config
    eslint.config.js
    )是当前的标准格式。从ESLint v9开始,旧版的
    .eslintrc.*
    格式已被弃用。
  • 配置对象按顺序合并——对于同一规则,后定义的对象会覆盖先定义的对象。
  • 规则级别
    "off"
    (0) |
    "warn"
    (1) |
    "error"
    (2)。
  • 插件可为ESLint扩展额外的规则、处理器和语言支持。引用格式为
    pluginName/ruleName

Setup

设置步骤

Quick initialization (recommended)

快速初始化(推荐)

bash
npm init @eslint/config@latest
This generates
eslint.config.js
interactively. Requires Node.js
^20.19.0
,
^22.13.0
, or
>=24
.
bash
npm init @eslint/config@latest
该命令会交互式生成
eslint.config.js
文件。要求Node.js版本为
^20.19.0
^22.13.0
>=24

Manual setup

手动设置

bash
npm install --save-dev eslint@latest @eslint/js@latest
Create
eslint.config.js
:
js
import { defineConfig } from "eslint/config";
import js from "@eslint/js";

export default defineConfig([
  {
    files: ["**/*.js"],
    plugins: { js },
    extends: ["js/recommended"],
    rules: {
      "no-unused-vars": "warn",
      "no-undef": "error",
    },
  },
]);
Run linting:
bash
npx eslint src/
bash
npm install --save-dev eslint@latest @eslint/js@latest
创建
eslint.config.js
文件:
js
import { defineConfig } from "eslint/config";
import js from "@eslint/js";

export default defineConfig([
  {
    files: ["**/*.js"],
    plugins: { js },
    extends: ["js/recommended"],
    rules: {
      "no-unused-vars": "warn",
      "no-undef": "error",
    },
  },
]);
运行代码检查:
bash
npx eslint src/

Flat Config Structure

扁平配置结构

Every configuration object accepts these keys:
KeyPurpose
name
Label for debugging (use
plugin/scope
convention)
files
Glob patterns this object applies to
ignores
Glob patterns to exclude (global if no other keys present)
extends
Inherit from plugin configs, shareable configs, or objects
plugins
Register plugins by namespace
rules
Rule names mapped to severity or
[severity, ...options]
languageOptions
ecmaVersion
,
sourceType
,
globals
,
parser
,
parserOptions
linterOptions
noInlineConfig
,
reportUnusedDisableDirectives
,
reportUnusedInlineConfigs
settings
Shared data available to all rules
processor
Extracts JS from non-JS files (e.g., Markdown)
每个配置对象支持以下键:
键名用途
name
调试用的标签(遵循
plugin/scope
命名规范)
files
该配置对象适用的Glob模式
ignores
要排除的Glob模式(若没有其他键则为全局生效)
extends
继承插件配置、可共享配置或其他配置对象
plugins
按命名空间注册插件
rules
规则名称与级别或
[级别, ...选项]
的映射
languageOptions
ecmaVersion
sourceType
globals
parser
parserOptions
linterOptions
noInlineConfig
reportUnusedDisableDirectives
reportUnusedInlineConfigs
settings
所有规则均可访问的共享数据
processor
从非JS文件中提取JS代码(如Markdown)

File targeting

文件目标定位

js
// Apply rules only to source files
{ files: ["src/**/*.{js,ts}"], rules: { ... } }

// Apply rules to all except tests
{ files: ["**/*.js"], ignores: ["**/*.test.js"], rules: { ... } }
js
// 仅对源码文件应用规则
{ files: ["src/**/*.{js,ts}"], rules: { ... } }

// 对所有文件应用规则,除了测试文件
{ files: ["**/*.js"], ignores: ["**/*.test.js"], rules: { ... } }

Global ignores (use
globalIgnores
)

全局忽略(使用
globalIgnores

js
import { defineConfig, globalIgnores } from "eslint/config";

export default defineConfig([
  globalIgnores(["dist/", "coverage/", "*.min.js"]),
  // other config objects...
]);
Use
globalIgnores()
— not bare
ignores
keys — for project-wide exclusions. This is the clearest and least error-prone pattern.
js
import { defineConfig, globalIgnores } from "eslint/config";

export default defineConfig([
  globalIgnores(["dist/", "coverage/", "*.min.js"]),
  // 其他配置对象...
]);
请使用
globalIgnores()
而非单独的
ignores
键来设置项目级别的全局排除规则,这是最清晰且最不易出错的方式。

Import
.gitignore
patterns

导入
.gitignore
规则

js
import { includeIgnoreFile } from "@eslint/compat";
import { fileURLToPath } from "node:url";

const gitignorePath = fileURLToPath(new URL(".gitignore", import.meta.url));

export default defineConfig([
  includeIgnoreFile(gitignorePath),
  // ...
]);
js
import { includeIgnoreFile } from "@eslint/compat";
import { fileURLToPath } from "node:url";

const gitignorePath = fileURLToPath(new URL(".gitignore", import.meta.url));

export default defineConfig([
  includeIgnoreFile(gitignorePath),
  // ...
]);

Rule Configuration Best Practices

规则配置最佳实践

Prefer
"error"
for enforced standards

优先使用
"error"
级别强制执行标准

Use
"error"
for rules that block bad code from merging. Reserve
"warn"
for violations that require human judgment or incremental adoption.
js
rules: {
  "no-var": "error",          // always use const/let
  "prefer-const": "error",    // enforce immutability where possible
  "eqeqeq": ["error", "always"], // ban == in favor of ===
  "no-console": "warn",       // flag but don't block during development
}
对阻止不良代码合并的规则使用
"error"
级别。仅对需要人工判断或逐步推行的违规情况使用
"warn"
级别。
js
rules: {
  "no-var": "error",          // 始终使用const/let
  "prefer-const": "error",    // 尽可能强制执行不可变性
  "eqeqeq": ["error", "always"], // 禁止使用==,改用===
  "no-console": "warn",       // 开发期间标记但不阻止
}

Disable inline comments sparingly

谨慎使用内联注释禁用规则

Use
// eslint-disable-next-line rule-name -- reason
with a mandatory reason. Never disable wholesale with
/* eslint-disable */
without scoping and justification.
js
// eslint-disable-next-line no-console -- CLI entrypoint needs output
console.log("Starting server...");
Enable detection of stale disable comments:
js
linterOptions: {
  reportUnusedDisableDirectives: "error",
}
使用
// eslint-disable-next-line rule-name -- 原因
格式,且必须注明原因。切勿无范围和理由地使用
/* eslint-disable */
全局禁用规则。
js
// eslint-disable-next-line no-console -- CLI入口需要输出日志
console.log("Starting server...");
启用对过时禁用注释的检测:
js
linterOptions: {
  reportUnusedDisableDirectives: "error",
}

File-pattern overrides instead of inline disables

使用文件模式覆盖而非内联禁用

Disable rules for test files via configuration, not inline comments:
js
{
  files: ["**/*.test.{js,ts}", "**/*.spec.{js,ts}"],
  rules: {
    "no-unused-expressions": "off", // chai/jest assertions
  },
}
通过配置而非内联注释为测试文件禁用规则:
js
{
  files: ["**/*.test.{js,ts}", "**/*.spec.{js,ts}"],
  rules: {
    "no-unused-expressions": "off", // 适配chai/jest断言语法
  },
}

Plugin Usage

插件使用

Register and use a plugin

注册并使用插件

js
import jsdoc from "eslint-plugin-jsdoc";
import { defineConfig } from "eslint/config";

export default defineConfig([
  {
    files: ["**/*.js"],
    plugins: { jsdoc },
    rules: {
      "jsdoc/require-description": "error",
      "jsdoc/check-values": "error",
    },
  },
]);
The plugin namespace is the property name in
plugins
. Convention: strip the
eslint-plugin-
prefix.
js
import jsdoc from "eslint-plugin-jsdoc";
import { defineConfig } from "eslint/config";

export default defineConfig([
  {
    files: ["**/*.js"],
    plugins: { jsdoc },
    rules: {
      "jsdoc/require-description": "error",
      "jsdoc/check-values": "error",
    },
  },
]);
插件的命名空间为
plugins
对象中的属性名。约定:去掉
eslint-plugin-
前缀。

Extend a plugin's recommended config

继承插件的推荐配置

js
import react from "eslint-plugin-react";
import { defineConfig } from "eslint/config";

export default defineConfig([
  {
    files: ["**/*.{jsx,tsx}"],
    plugins: { react },
    extends: ["react/recommended"],
    languageOptions: {
      parserOptions: { ecmaFeatures: { jsx: true } },
    },
  },
]);
js
import react from "eslint-plugin-react";
import { defineConfig } from "eslint/config";

export default defineConfig([
  {
    files: ["**/*.{jsx,tsx}"],
    plugins: { react },
    extends: ["react/recommended"],
    languageOptions: {
      parserOptions: { ecmaFeatures: { jsx: true } },
    },
  },
]);

TypeScript Support

TypeScript 支持

Install the TypeScript parser and plugin:
bash
npm install --save-dev typescript-eslint
js
import tseslint from "typescript-eslint";
import { defineConfig } from "eslint/config";

export default defineConfig([
  ...tseslint.configs.recommended,
  {
    files: ["**/*.ts", "**/*.tsx"],
    rules: {
      "@typescript-eslint/no-explicit-any": "warn",
      "@typescript-eslint/explicit-function-return-type": "off",
    },
  },
]);
安装TypeScript解析器和插件:
bash
npm install --save-dev typescript-eslint
js
import tseslint from "typescript-eslint";
import { defineConfig } from "eslint/config";

export default defineConfig([
  ...tseslint.configs.recommended,
  {
    files: ["**/*.ts", "**/*.tsx"],
    rules: {
      "@typescript-eslint/no-explicit-any": "warn",
      "@typescript-eslint/explicit-function-return-type": "off",
    },
  },
]);

Linter Options

检查器选项

js
{
  linterOptions: {
    noInlineConfig: false,                    // allow inline eslint comments
    reportUnusedDisableDirectives: "error",   // fail on stale disables
    reportUnusedInlineConfigs: "warn",        // warn on redundant inline configs
  },
}
js
{
  linterOptions: {
    noInlineConfig: false,                    // 允许使用内联eslint注释
    reportUnusedDisableDirectives: "error",   // 对过时的禁用注释抛出错误
    reportUnusedInlineConfigs: "warn",        // 对冗余的内联配置发出警告
  },
}

Debugging Configuration

配置调试

Inspect which config objects apply to a file:
bash
npx eslint --inspect-config        # Opens config inspector UI
npx eslint --print-config file.js  # Prints merged config for a file
查看哪些配置对象应用于某个文件:
bash
npx eslint --inspect-config        # 打开配置检查器UI
npx eslint --print-config file.js  # 打印某个文件的合并后配置

CI/CD Integration

CI/CD 集成

Add to
package.json
:
json
{
  "scripts": {
    "lint": "eslint src/",
    "lint:fix": "eslint src/ --fix"
  }
}
Run
npm run lint
in CI. ESLint exits with code
1
when any
"error"
-severity rule triggers, blocking merges.
package.json
中添加脚本:
json
{
  "scripts": {
    "lint": "eslint src/",
    "lint:fix": "eslint src/ --fix"
  }
}
在CI中运行
npm run lint
。当任何
"error"
级别规则被触发时,ESLint会以代码
1
退出,从而阻止代码合并。

Quick Reference: Rule Severity

快速参考:规则级别

ValueMeaning
"off"
/
0
Disabled
"warn"
/
1
Warning (exit code 0)
"error"
/
2
Error (exit code 1)
含义
"off"
/
0
禁用
"warn"
/
1
警告(退出代码0)
"error"
/
2
错误(退出代码1)

Additional Resources

额外资源

Reference Files

参考文档

  • references/configuration-guide.md
    — Detailed flat config patterns, cascading, TypeScript config files, monorepo setup
  • references/rules-and-plugins.md
    — Commonly used rules reference and popular plugin ecosystem
  • references/configuration-guide.md
    — 详细的扁平配置模式、级联规则、TypeScript配置文件、单仓库设置指南
  • references/rules-and-plugins.md
    — 常用规则参考和热门插件生态介绍

Example Files

示例文件

  • examples/eslint.config.js
    — Production-ready config for a TypeScript project with React
  • examples/eslint.config.js
    — 适用于TypeScript+React项目的生产级配置