Skip to content
On this page

ESLint 安装与配置

本章详细介绍 ESLint 的安装方法和各种配置选项,帮助您为项目设置合适的代码检查环境。

安装方法

使用 npm 安装

bash
# 全局安装(不推荐)
npm install -g eslint

# 项目本地安装(推荐)
npm install --save-dev eslint

# 初始化配置
npx eslint --init

使用 yarn 安装

bash
# 全局安装(不推荐)
yarn global add eslint

# 项目本地安装(推荐)
yarn add --dev eslint

# 初始化配置
yarn eslint --init

使用 pnpm 安装

bash
# 项目本地安装
pnpm add --save-dev eslint

# 初始化配置
pnpm eslint --init

项目初始化

交互式初始化

运行以下命令开始交互式配置:

bash
npx eslint --init

配置过程中需要回答以下问题:

  1. How would you like to use ESLint?

    • To check syntax only(仅检查语法)
    • To check syntax and find problems(检查语法并发现问题)
    • To check syntax, find problems, and enforce code style(检查语法、发现问题并强制代码风格)
  2. What type of modules does your project use?

    • JavaScript modules (import/export)
    • CommonJS (require/exports)
    • None of these
  3. Which framework does your project use?

    • React
    • Vue.js
    • None of these
  4. Does your project use TypeScript?

    • Yes
    • No
  5. Where does your code run?

    • Browser
    • Node
  6. How would you like to define a style guide?

    • Use a popular style guide(使用流行的风格指南)
    • Answer questions about your style(回答风格问题)
    • Inspect your JavaScript file directly(直接检查 JS 文件)
  7. Which format do you want your config file to be in?

    • JavaScript
    • YAML
    • JSON

手动配置

如果不想使用交互式初始化,可以手动创建配置文件:

bash
# 创建空的配置文件
touch .eslintrc.js

配置文件详解

JavaScript 配置文件

javascript
// .eslintrc.js
module.exports = {
  // 环境配置
  env: {
    browser: true,    // 启用浏览器全局变量
    es2021: true,     // 启用 ES2021 功能
    node: true,       // 启用 Node.js 全局变量
    jest: true,       // 启用 Jest 全局变量
    mocha: true       // 启用 Mocha 全局变量
  },

  // 解析器配置
  parser: '@babel/eslint-parser',  // 使用 Babel 解析器
  parserOptions: {
    ecmaVersion: 2021,              // ES 版本
    sourceType: 'module',           // 模块类型
    ecmaFeatures: {
      jsx: true,                    // 支持 JSX
      globalReturn: false,          // 不支持全局 return
      impliedStrict: true           // 使用严格模式
    },
    requireConfigFile: false,
    babelOptions: {
      presets: ['@babel/preset-react']
    }
  },

  // 继承的配置
  extends: [
    'eslint:recommended',           // ESLint 推荐规则
    'airbnb',                      // Airbnb 风格
    'plugin:react/recommended',     // React 推荐规则
    'plugin:import/errors',        // Import 错误规则
    'plugin:import/warnings'       // Import 警告规则
  ],

  // 使用的插件
  plugins: [
    'react',                       // React 插件
    'import',                      // Import 插件
    'jsx-a11y'                     // 可访问性插件
  ],

  // 具体规则配置
  rules: {
    'no-console': 'warn',          // 禁止 console,警告级别
    'no-debugger': 'error',        // 禁止 debugger,错误级别
    'semi': ['error', 'always'],   // 要求使用分号
    'quotes': ['error', 'single', { 'avoidEscape': true }], // 使用单引号
    'comma-dangle': ['error', 'never'] // 禁止尾随逗号
  },

  // 全局变量
  globals: {
    Atomics: 'readonly',
    SharedArrayBuffer: 'readonly',
    myGlobal: 'writable'
  },

  // 覆盖配置
  overrides: [
    {
      files: ['**/*.test.js', '**/*.spec.js'],
      env: {
        jest: true
      },
      rules: {
        'no-unused-expressions': 'off'
      }
    },
    {
      files: ['**/*.ts', '**/*.tsx'],
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      extends: [
        '@typescript-eslint/recommended'
      ],
      rules: {
        '@typescript-eslint/explicit-function-return-type': 'warn'
      }
    }
  ]
};

package.json 中的配置

您也可以在 package.json 中配置 ESLint:

json
{
  "name": "my-project",
  "version": "1.0.0",
  "eslintConfig": {
    "env": {
      "browser": true,
      "es2021": true
    },
    "extends": [
      "eslint:recommended"
    ],
    "parserOptions": {
      "ecmaVersion": 12,
      "sourceType": "module"
    },
    "rules": {
      "no-console": "warn"
    }
  },
  "eslintIgnore": [
    "node_modules/",
    "dist/"
  ]
}

配置文件优先级

ESLint 会按以下顺序查找配置文件,找到第一个就会停止:

  1. .eslintrc.js
  2. .eslintrc.cjs
  3. .eslintrc.yaml
  4. .eslintrc.yml
  5. .eslintrc.json
  6. package.json 中的 eslintConfig 字段

配置继承详解

使用推荐规则

javascript
module.exports = {
  extends: [
    'eslint:recommended'  // ESLint 官方推荐规则
  ],
  // 推荐规则会开启以下规则:
  // - no-unsafe-finally
  // - no-unsafe-negation
  // - use-isnan
  // - valid-typeof
  // 等等
};

使用第三方规则集

javascript
module.exports = {
  extends: [
    'airbnb',           // Airbnb 风格
    'standard',         // Standard 风格
    'google',          // Google 风格
    'prettier'         // Prettier 配置(用于禁用冲突规则)
  ]
};

插件安装与配置

安装常用插件

bash
# React 相关插件
npm install --save-dev eslint-plugin-react eslint-plugin-jsx-a11y eslint-plugin-react-hooks

# Import 相关插件
npm install --save-dev eslint-plugin-import

# TypeScript 相关插件
npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser

# Prettier 集成插件
npm install --save-dev eslint-config-prettier eslint-plugin-prettier

插件配置示例

javascript
module.exports = {
  plugins: [
    'react',
    'import',
    '@typescript-eslint',
    'prettier'
  ],
  
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    '@typescript-eslint/recommended',
    'prettier'  // 必须放在最后,用于关闭与 Prettier 冲突的规则
  ],
  
  settings: {
    react: {
      version: 'detect'  // 自动检测 React 版本
    }
  }
};

解析器配置

Babel 解析器

bash
npm install --save-dev @babel/core @babel/eslint-parser
javascript
module.exports = {
  parser: '@babel/eslint-parser',
  parserOptions: {
    requireConfigFile: false,
    babelOptions: {
      presets: [
        '@babel/preset-env',
        '@babel/preset-react'
      ]
    },
    ecmaVersion: 2021,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  }
};

TypeScript 解析器

bash
npm install --save-dev @typescript-eslint/parser
javascript
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2021,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    },
    // 额外的 TypeScript 特定选项
    warnOnUnsupportedTypeScriptVersion: true
  },
  plugins: [
    '@typescript-eslint'
  ],
  extends: [
    '@typescript-eslint/recommended'
  ]
};

覆盖配置(Overrides)

覆盖配置允许您为特定文件应用不同的规则:

javascript
module.exports = {
  // 通用配置
  rules: {
    'no-console': 'error'
  },
  
  overrides: [
    // 测试文件配置
    {
      files: ['**/*.test.js', '**/*.spec.js', '**/*.test.tsx'],
      env: {
        jest: true,
        'jest/globals': true
      },
      plugins: ['jest'],
      extends: ['plugin:jest/recommended'],
      rules: {
        'no-console': 'off',  // 测试文件中允许 console
        'jest/expect-expect': 'off'
      }
    },
    
    // 配置文件配置
    {
      files: ['*.config.js', '*.conf.js'],
      env: {
        node: true
      },
      rules: {
        'no-console': 'off'  // 配置文件中允许 console
      }
    },
    
    // TypeScript 文件配置
    {
      files: ['*.ts', '*.tsx'],
      parser: '@typescript-eslint/parser',
      plugins: ['@typescript-eslint'],
      extends: ['@typescript-eslint/recommended'],
      rules: {
        '@typescript-eslint/explicit-function-return-type': 'warn'
      }
    }
  ]
};

忽略文件配置

.eslintignore 文件

bash
# .eslintignore
node_modules/           # 忽略 node_modules
dist/                 # 忽略构建目录
build/                # 忽略构建目录
*.min.js              # 忽略压缩文件
coverage/             # 忽略覆盖率目录
.next/                # 忽略 Next.js 目录
.nuxt/                # 忽略 Nuxt.js 目录
*.d.ts               # 忽略类型定义文件

在配置文件中指定忽略文件

javascript
module.exports = {
  ignorePatterns: [
    'node_modules/',
    'dist/',
    'build/',
    '*.min.js',
    'coverage/',
    '.next/',
    '.nuxt/',
    '*.d.ts'
  ]
};

配置验证

验证配置文件是否正确:

bash
# 验证配置文件
npx eslint --print-config src/index.js

# 检查配置是否有效
npx eslint --print-config src/index.js > /dev/null && echo "Config is valid" || echo "Config has errors"

小结

本章详细介绍了 ESLint 的安装和配置方法,包括各种配置文件格式、插件使用、解析器配置等。正确的配置是有效使用 ESLint 的基础,下一章我们将深入了解 ESLint 的各种规则。