eslint
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseESLint Best Practices
ESLint 最佳实践
Provides guidance for configuring ESLint using the modern flat config format (), selecting and tuning rules, managing plugins, and integrating linting into CI/CD workflows.
eslint.config.js本文提供使用现代扁平配置格式()配置ESLint、选择和调整规则、管理插件,以及将代码检查集成到CI/CD工作流中的指导。
eslint.config.jsCore Concepts
核心概念
- Flat config () is the current standard. The legacy
eslint.config.jsformat is deprecated as of ESLint v9..eslintrc.* - Configuration objects are merged in order — later objects override earlier ones for the same rule.
- Rule severities: (0) |
"off"(1) |"warn"(2)."error" - Plugins extend ESLint with additional rules, processors, and languages. Reference as .
pluginName/ruleName
- Flat config()是当前的标准格式。从ESLint v9开始,旧版的
eslint.config.js格式已被弃用。.eslintrc.* - 配置对象按顺序合并——对于同一规则,后定义的对象会覆盖先定义的对象。
- 规则级别:(0) |
"off"(1) |"warn"(2)。"error" - 插件可为ESLint扩展额外的规则、处理器和语言支持。引用格式为。
pluginName/ruleName
Setup
设置步骤
Quick initialization (recommended)
快速初始化(推荐)
bash
npm init @eslint/config@latestThis generates interactively. Requires Node.js , , or .
eslint.config.js^20.19.0^22.13.0>=24bash
npm init @eslint/config@latest该命令会交互式生成文件。要求Node.js版本为、或。
eslint.config.js^20.19.0^22.13.0>=24Manual setup
手动设置
bash
npm install --save-dev eslint@latest @eslint/js@latestCreate :
eslint.config.jsjs
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.jsjs
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:
| Key | Purpose |
|---|---|
| Label for debugging (use |
| Glob patterns this object applies to |
| Glob patterns to exclude (global if no other keys present) |
| Inherit from plugin configs, shareable configs, or objects |
| Register plugins by namespace |
| Rule names mapped to severity or |
| |
| |
| Shared data available to all rules |
| Extracts JS from non-JS files (e.g., Markdown) |
每个配置对象支持以下键:
| 键名 | 用途 |
|---|---|
| 调试用的标签(遵循 |
| 该配置对象适用的Glob模式 |
| 要排除的Glob模式(若没有其他键则为全局生效) |
| 继承插件配置、可共享配置或其他配置对象 |
| 按命名空间注册插件 |
| 规则名称与级别或 |
| |
| |
| 所有规则均可访问的共享数据 |
| 从非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全局忽略(使用globalIgnores
)
globalIgnoresjs
import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([
globalIgnores(["dist/", "coverage/", "*.min.js"]),
// other config objects...
]);Use — not bare keys — for project-wide exclusions. This is the clearest and least error-prone pattern.
globalIgnores()ignoresjs
import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([
globalIgnores(["dist/", "coverage/", "*.min.js"]),
// 其他配置对象...
]);请使用而非单独的键来设置项目级别的全局排除规则,这是最清晰且最不易出错的方式。
globalIgnores()ignoresImport .gitignore
patterns
.gitignore导入.gitignore
规则
.gitignorejs
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"优先使用"error"
级别强制执行标准
"error"Use for rules that block bad code from merging. Reserve for violations that require human judgment or incremental adoption.
"error""warn"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 with a mandatory reason. Never disable wholesale with without scoping and justification.
// eslint-disable-next-line rule-name -- reason/* eslint-disable */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 . Convention: strip the prefix.
pluginseslint-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",
},
},
]);插件的命名空间为对象中的属性名。约定:去掉前缀。
pluginseslint-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-eslintjs
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-eslintjs
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.jsonjson
{
"scripts": {
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix"
}
}Run in CI. ESLint exits with code when any -severity rule triggers, blocking merges.
npm run lint1"error"在中添加脚本:
package.jsonjson
{
"scripts": {
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix"
}
}在CI中运行。当任何级别规则被触发时,ESLint会以代码退出,从而阻止代码合并。
npm run lint"error"1Quick Reference: Rule Severity
快速参考:规则级别
| Value | Meaning |
|---|---|
| Disabled |
| Warning (exit code 0) |
| Error (exit code 1) |
| 值 | 含义 |
|---|---|
| 禁用 |
| 警告(退出代码0) |
| 错误(退出代码1) |
Additional Resources
额外资源
Reference Files
参考文档
- — Detailed flat config patterns, cascading, TypeScript config files, monorepo setup
references/configuration-guide.md - — Commonly used rules reference and popular plugin ecosystem
references/rules-and-plugins.md
- — 详细的扁平配置模式、级联规则、TypeScript配置文件、单仓库设置指南
references/configuration-guide.md - — 常用规则参考和热门插件生态介绍
references/rules-and-plugins.md
Example Files
示例文件
- — Production-ready config for a TypeScript project with React
examples/eslint.config.js
- — 适用于TypeScript+React项目的生产级配置
examples/eslint.config.js