Skip to content

ESLint

ESLint 是什么?

ESLint 是一个JavaScript 代码质量检查工具,用于:

  • 检测语法错误(如未定义变量、拼写错误)
  • 强制代码风格规范(如驼峰命名、引号使用)
  • 发现潜在问题(如未使用的变量、不安全的操作) 与 Prettier 不同,ESLint 更关注代码质量和逻辑问题,而不是格式细节。

ESLint 核心 API 配置

ESLint 通过 .eslintrc.js 或 .eslintrc.json 配置,主要包含以下部分:

js
module.exports = {
  // 基础配置
  "root": true,                     // 停止向上查找配置文件
  "env": {                          // 环境定义(提供全局变量)
    "browser": true,                // 浏览器环境
    "node": true,                   // Node.js 环境
    "es6": true,                    // ES6 环境
    "jest": true                    // Jest 测试环境
  },
  "parser": "@typescript-eslint/parser", // TypeScript 解析器
  "parserOptions": {                // 解析器选项
    "ecmaVersion": 2021,            // ES 版本
    "sourceType": "module",         // 模块类型('script' 或 'module')
    "ecmaFeatures": {               // ES 特性
      "jsx": true                   // 支持 JSX
    }
  },
  
  // 继承配置
  "extends": [
    "eslint:recommended",          // ESLint 推荐规则
    "plugin:react/recommended",    // React 插件推荐规则
    "plugin:@typescript-eslint/recommended", // TypeScript 插件推荐规则
    "prettier"                     // 关闭与 Prettier 冲突的规则
  ],
  
  // 插件配置
  "plugins": [
    "react",                       // React 插件
    "@typescript-eslint"           // TypeScript 插件
  ],
  
  // 全局变量配置
  "globals": {
    "fetch": "readonly",            // 声明 fetch 为只读全局变量
    "myGlobal": "writable"          // 声明 myGlobal 为可写全局变量
  },
  
  // 规则配置
  "rules": {
    // 错误级别: 0=关闭, 1=警告, 2=错误
    "no-console": 1,                // 禁止 console (警告级别)
    "no-debugger": 2,               // 禁止 debugger (错误级别)
    "semi": ["error", "always"],    // 强制使用分号
    "quotes": ["error", "single"],  // 强制使用单引号
    "indent": ["error", 2],         // 强制缩进为 2 空格
    "eqeqeq": "error",              // 强制使用 ===
    "no-unused-vars": ["error", { "vars": "all", "args": "after-used" }], // 禁止未使用变量
    "react/react-in-jsx-scope": "off", // 关闭 React 必须在 JSX 中引入的规则
    "@typescript-eslint/no-explicit-any": "warn" // 警告使用 any 类型
  },
  
  // 忽略文件
  "ignorePatterns": [
    "node_modules/",                // 忽略 node_modules
    "dist/"                         // 忽略 dist 目录
  ]
};

常用规则分类

基础语法规则

js
"no-var": "error",                 // 禁止使用 var
"prefer-const": "error",           // 要求使用 const 替代 let
"no-unreachable": "error",         // 禁止不可达代码
"no-extra-semi": "error",          // 禁止多余的分号

最佳实践规则

js
"eqeqeq": "error",                 // 强制使用 ===
"no-eval": "error",                // 禁止使用 eval
"no-with": "error",                // 禁止使用 with
"no-return-await": "error",        // 禁止不必要的 return await

变量规则

js
"no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], // 允许以下划线开头的未使用变量
"no-shadow": "error",              // 禁止变量声明覆盖外部变量
"no-use-before-define": "error",   // 禁止在定义前使用变量

React 特定规则

js
"react/prop-types": "off",         // 关闭 prop-types 检查(若使用 TypeScript)
"react/display-name": "off",       // 关闭组件显示名称检查
"react/jsx-key": "error",          // 强制 JSX 数组项有 key

配置与使用方法

安装 ESLint

bash
npm install eslint --save-dev

初始化配置

bash
npx eslint --init

此命令会生成 .eslintrc.js 配置文件,并根据你的选择安装相应的插件。

添加 npm 脚本

json
// package.json
{
  "scripts": {
    "lint": "eslint src --ext .js,.jsx,.ts,.tsx",
    "lint:fix": "eslint src --ext .js,.jsx,.ts,.tsx --fix"
  }
}

在 WebStorm 中集成

  • 打开 Settings > Languages & Frameworks > JavaScript > Code Quality Tools > ESLint
  • 选择 Automatic ESLint configuration
  • 启用 Run eslint --fix on save

忽略文件

创建 .eslintignore 文件:

text
node_modules/
dist/
build/

与 Prettier 配合使用

避免规则冲突,安装:

bash
npm install eslint-config-prettier --save-dev

在 .eslintrc.js 中添加:

js
extends: [
  // 其他配置...
  'prettier' // 必须放在最后,关闭与 Prettier 冲突的规则
]

总结

ESLint 通过灵活的配置,可以满足不同项目的代码质量要求。核心在于合理选择 extends 基础配置,并通过 rules 自定义规则。建议在新项目中使用 npx eslint --init 初始化,然后根据团队需求调整规则。