Skip to content

ESLint 使用配置指南

ESLint 是一个可配置的 JavaScript 代码检查工具,用于发现和修复代码中的问题,包括:

  • 语法错误
  • 潜在的 Bug
  • 代码风格问题
  • 不规范的写法

什么是 ESLint?

ESLint 是一个开源的 JavaScript 代码检查工具,由 Nicholas C. Zakas 于 2013 年创建。它通过静态分析代码来发现问题,可以在编码阶段就发现潜在的错误。

安装

安装 ESLint

bash
# 安装 ESLint
npm install --save-dev eslint

# 或使用 pnpm
pnpm add -D eslint

# 或使用 yarn
yarn add -D eslint

安装常用插件

bash
# TypeScript 支持
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin

# Vue 支持
npm install --save-dev eslint-plugin-vue

# React 支持
npm install --save-dev eslint-plugin-react eslint-plugin-react-hooks

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

# Vue 项目推荐
npm install --save-dev @vue/eslint-config-prettier

配置文件

初始化配置文件

bash
# 自动创建配置文件
npx eslint --init

.eslintrc.js 配置示例

javascript
module.exports = {
  // 指定环境
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  // 扩展配置
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended',
    'prettier', // 必须放在最后,覆盖其他配置
  ],
  // 解析器
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  // 插件
  plugins: ['@typescript-eslint', 'vue', 'prettier'],
  // 自定义规则
  rules: {
    // Prettier 规则
    'prettier/prettier': 'error',
    // 其他规则
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    '@typescript-eslint/no-explicit-any': 'warn',
    'vue/multi-word-component-names': 'off',
  },
  // 忽略文件
  ignorePatterns: ['dist', 'node_modules', '*.config.js'],
}

.eslintrc.json 配置示例

json
{
  "env": {
    "browser": true,
    "es2021": true,
    "node": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "rules": {
    "prettier/prettier": "error",
    "no-console": "warn",
    "no-debugger": "warn"
  }
}

.eslintrc.yaml 配置示例

yaml
env:
  browser: true
  es2021: true
  node: true

extends:
  - eslint:recommended
  - plugin:@typescript-eslint/recommended
  - prettier

parser: '@typescript-eslint/parser'

parserOptions:
  ecmaVersion: latest
  sourceType: module

plugins:
  - '@typescript-eslint'
  - prettier

rules:
  prettier/prettier: error
  no-console: warn
  no-debugger: warn

.eslintignore 文件

创建 .eslintignore 文件指定不需要检查的文件:

gitignore
# 依赖
node_modules
package-lock.json
pnpm-lock.yaml
yarn.lock

# 构建产物
dist
build
*.min.js

# 日志
*.log

# 配置文件
*.config.js

常用规则配置

代码质量规则

javascript
rules: {
  // 变量相关
  'no-unused-vars': 'warn',           // 未使用的变量
  'no-undef': 'error',                // 未定义的变量
  'no-duplicate-imports': 'error',    // 重复导入
  
  // 代码规范
  'no-var': 'error',                  // 禁止使用 var
  'prefer-const': 'warn',             // 优先使用 const
  'no-eval': 'error',                 // 禁止使用 eval
  'no-implied-eval': 'error',         // 禁止使用隐式 eval
  
  // 错误处理
  'no-throw-literal': 'error',        // 禁止抛出字面量
  'prefer-promise-reject-errors': 'error', // Promise reject 必须是 Error
}

代码风格规则

javascript
rules: {
  // 分号
  'semi': ['error', 'always'],        // 要求分号
  
  // 引号
  'quotes': ['error', 'single'],      // 使用单引号
  
  // 缩进(通常由 Prettier 处理)
  'indent': ['error', 2],             // 缩进 2 空格
  
  // 逗号
  'comma-dangle': ['error', 'always-multiline'], // 尾随逗号
  
  // 括号
  'curly': ['error', 'all'],          // 要求使用大括号
  'brace-style': ['error', '1tbs'],   // 大括号风格
}

Vue 特定规则

javascript
rules: {
  // 组件命名
  'vue/multi-word-component-names': 'off', // 允许单单词组件名
  'vue/component-name-in-template-casing': ['error', 'PascalCase'],
  
  // HTML 相关
  'vue/html-self-closing': 'error',   // HTML 自闭合标签
  'vue/attribute-hyphenation': 'error', // 属性使用短横线命名
  'vue/v-on-event-hyphenation': 'error', // 事件使用短横线命名
  
  // 代码顺序
  'vue/component-tags-order': ['error', {
    order: ['script', 'template', 'style']
  }],
}

TypeScript 规则

javascript
rules: {
  // 类型相关
  '@typescript-eslint/explicit-function-return-type': 'off',
  '@typescript-eslint/no-explicit-any': 'warn',
  '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
  '@typescript-eslint/no-non-null-assertion': 'warn',
  
  // 代码规范
  '@typescript-eslint/prefer-const': 'error',
  '@typescript-eslint/no-var-requires': 'error', // 禁止使用 require
}

Vue 项目配置

Vue 3 + TypeScript + Vite

javascript
// .eslintrc.cjs
module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/eslint-config-typescript',
    '@vue/eslint-config-prettier',
  ],
  parserOptions: {
    ecmaVersion: 'latest',
  },
  rules: {
    'vue/multi-word-component-names': 'off',
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
  },
}

React 项目配置

React + TypeScript

javascript
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:react-hooks/recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', 'react-hooks', '@typescript-eslint'],
  settings: {
    react: {
      version: 'detect',
    },
  },
  rules: {
    'react/react-in-jsx-scope': 'off',
    'react/prop-types': 'off',
  },
}

与 Prettier 集成

解决冲突

ESLint 和 Prettier 可能会有规则冲突,需要正确配置。

javascript
// .eslintrc.js
module.exports = {
  extends: [
    'eslint:recommended',
    'prettier', // 必须放在最后,关闭与 Prettier 冲突的规则
  ],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error', // 将 Prettier 的格式化问题作为 ESLint 错误
  },
}

在 VSCode 中配置

创建 .vscode/settings.json

json
{
  // ESLint 配置
  "eslint.enable": true,
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "vue"
  ],
  
  // 保存时自动修复
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  
  // 显示 ESLint 状态
  "eslint.alwaysShowStatus": true
}

在 package.json 中添加脚本

json
{
  "scripts": {
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx,.vue",
    "lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx,.vue --fix",
    "lint:report": "eslint . --ext .js,.jsx,.ts,.tsx,.vue --format html --output-file eslint-report.html"
  }
}

实际应用场景

1. Git Hooks 集成

使用 husky 和 lint-staged 在提交前自动检查:

bash
# 安装依赖
npm install --save-dev husky lint-staged
json
// package.json
{
  "lint-staged": {
    "*.{js,jsx,ts,tsx,vue}": [
      "eslint --fix"
    ]
  }
}
bash
# 初始化 husky
npx husky install

# 添加 pre-commit hook
npx husky add .husky/pre-commit "npx lint-staged"

2. CI/CD 集成

在 GitHub Actions 中配置:

yaml
# .github/workflows/lint.yml
name: Lint

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npm run lint

3. 自定义规则

创建自定义 ESLint 规则:

javascript
// eslint-local-rules.js
module.exports = {
  'no-console-time': {
    create(context) {
      return {
        CallExpression(node) {
          if (node.callee.object?.name === 'console' && 
              node.callee.property?.name === 'time') {
            context.report({
              node,
              message: '禁止使用 console.time',
            })
          }
        },
      }
    },
  },
}

.eslintrc.js 中使用:

javascript
module.exports = {
  plugins: ['local-rules'],
  rules: {
    'local-rules/no-console-time': 'error',
  },
}

常见问题

1. ESLint 和 Prettier 冲突

问题:格式化后 ESLint 报错

解决方案

  • 确保 eslint-config-prettier 在 extends 数组的最后
  • 使用 eslint-plugin-prettier 将 Prettier 作为 ESLint 规则运行

2. 解析错误

问题:ESLint 无法解析某些语法

解决方案

  • 检查 parserparserOptions 配置
  • 确保安装了正确的解析器插件
  • 对于 TypeScript,使用 @typescript-eslint/parser

3. 规则不生效

问题:配置了规则但没有效果

解决方案

  • 检查配置文件格式是否正确
  • 确保规则名称拼写正确
  • 检查是否有其他配置文件覆盖了规则

最佳实践

  1. 统一配置:团队使用相同的配置文件
  2. 渐进式引入:不要一次性开启所有规则
  3. 定期更新:保持 ESLint 和插件版本更新
  4. 自定义规则:根据项目需求定制规则
  5. 文档化:记录重要的配置决策和原因
  6. 自动化:使用 Git Hooks 和 CI/CD 自动检查

推荐配置模板

基础配置(JavaScript)

javascript
// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: ['eslint:recommended', 'prettier'],
  plugins: ['prettier'],
  rules: {
    'prettier/prettier': 'error',
    'no-console': 'warn',
    'no-debugger': 'warn',
  },
}

Vue 3 + TypeScript

javascript
// .eslintrc.cjs
module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'eslint:recommended',
    '@vue/eslint-config-typescript',
    '@vue/eslint-config-prettier',
  ],
  rules: {
    'vue/multi-word-component-names': 'off',
  },
}

最后更新:2025年

这是我的个人文档