跳转至

ESLint 代码检查

一句话概述:ESLint 是 JavaScript/TypeScript 最主流的代码检查工具,自动发现和修复代码中的问题(语法错误、风格不统一、潜在 Bug),v9 采用全新的 Flat Config 配置方式。

核心知识点

概念白话解释
Linter代码检查工具,扫描代码找问题,不运行代码
Flat Configv9 的新配置方式,用 eslint.config.mjs 文件,更简洁
规则(Rule)每条检查规则,比如"不允许用 var"
插件(Plugin)扩展规则的包,比如 @typescript-eslint 添加 TS 规则
预设(Config)一组规则的集合,比如 eslint:recommended
--fix自动修复能修复的问题

安装配置

# 初始化 ESLint(交互式,自动生成配置)
npm init @eslint/config@latest  # 回答问题后自动安装依赖和生成配置

# 或者手动安装
npm install -D eslint  # 安装 ESLint
npm install -D @eslint/js  # 官方推荐规则
npm install -D typescript-eslint  # TypeScript 支持
npm install -D eslint-plugin-react  # React 支持(如需要)

Flat Config 配置(v9+)

// eslint.config.mjs - 新版扁平配置
import js from '@eslint/js'  // 官方推荐规则
import tseslint from 'typescript-eslint'  // TypeScript ESLint
import react from 'eslint-plugin-react'  // React 插件

export default [
  js.configs.recommended,  // 启用 ESLint 推荐规则
  ...tseslint.configs.recommended,  // 启用 TypeScript 推荐规则

  {
    files: ['**/*.{ts,tsx}'],  // 只对 TS/TSX 文件生效
    plugins: {
      react,  // 注册 React 插件
    },
    rules: {
      'no-unused-vars': 'off',  // 关掉 JS 版(用 TS 版替代)
      '@typescript-eslint/no-unused-vars': 'warn',  // 未使用变量警告
      '@typescript-eslint/no-explicit-any': 'warn',  // 不建议用 any
      'react/react-in-jsx-scope': 'off',  // React 17+ 不需要导入 React
      'no-console': 'warn',  // console.log 警告
    },
  },

  {
    ignores: ['dist/', 'node_modules/', '*.config.js'],  // 忽略的文件/目录
  },
]

基本使用

# 检查代码
npx eslint src/  # 检查 src 目录
npx eslint src/ --fix  # 检查并自动修复
npx eslint "src/**/*.{ts,tsx}"  # 指定文件模式
npx eslint . --max-warnings 0  # 有警告也算失败(CI 用)

# package.json 脚本
# "lint": "eslint src/",
# "lint:fix": "eslint src/ --fix"

规则级别

rules: {
  'no-console': 'off',   // 0 / "off": 关闭规则
  'no-console': 'warn',  // 1 / "warn": 警告(不阻止)
  'no-console': 'error', // 2 / "error": 错误(阻止)

  // 带选项的规则
  'no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],  // 以 _ 开头的参数忽略
}

高级用法

与 Prettier 配合

npm install -D prettier eslint-config-prettier  # 安装 Prettier 和兼容配置
// eslint.config.mjs
import prettier from 'eslint-config-prettier'  // Prettier 兼容配置

export default [
  js.configs.recommended,
  ...tseslint.configs.recommended,
  prettier,  // 放最后!关闭与 Prettier 冲突的 ESLint 规则
]

VS Code 集成

// .vscode/settings.json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"  // 保存时自动修复 ESLint 问题
  },
  "eslint.validate": ["javascript", "typescript", "javascriptreact", "typescriptreact"]
}

自定义规则

// eslint.config.mjs - 按文件类型设置不同规则
export default [
  // 源码文件:严格规则
  {
    files: ['src/**/*.ts'],
    rules: {
      'no-console': 'error',  // 源码不允许 console
      '@typescript-eslint/no-explicit-any': 'error',  // 禁止 any
    },
  },
  // 测试文件:宽松规则
  {
    files: ['**/*.test.ts', '**/*.spec.ts'],
    rules: {
      'no-console': 'off',  // 测试可以 console
      '@typescript-eslint/no-explicit-any': 'off',  // 测试可以用 any
    },
  },
]

常见报错

报错信息原因解决方案
Parsing error文件解析失败确保安装了对应语言的 parser
Definition for rule 'xxx' was not found规则不存在检查插件是否安装并注册
.eslintrc 和 flat config 冲突混用新旧配置删掉 .eslintrc,只用 eslint.config.mjs
no-unused-vars 误报 TS 类型用了 JS 版规则改用 @typescript-eslint/no-unused-vars
与 Prettier 冲突格式规则重叠eslint-config-prettier 到最后

速查表

# CLI 命令
npx eslint .                        # 检查当前目录
npx eslint . --fix                  # 自动修复
npx eslint . --max-warnings 0       # 警告也算失败
npx eslint --print-config file.ts   # 查看某文件的生效规则
npx eslint --debug .                # 调试模式

# 行内注释控制
/* eslint-disable */           // 禁用所有规则(整个文件)
/* eslint-enable */            // 重新启用
/* eslint-disable no-console */  // 禁用某条规则
// eslint-disable-next-line    // 只禁用下一行
// eslint-disable-line         // 只禁用当前行

# 常用规则
no-unused-vars        # 未使用的变量
no-console            # console 语句
no-debugger           # debugger 语句
eqeqeq                # 必须用 === 不用 ==
no-var                # 禁止 var,用 let/const
prefer-const          # 能用 const 就用 const
no-undef              # 禁止未定义变量

参考:ESLint 官网 | Flat Config 迁移指南 | 规则列表