Appearance
ESLint 配置文件
ESLint 配置文件用于定义代码检查规则、环境、解析器等设置。本章详细介绍各种配置文件格式和配置选项。
配置文件格式
ESLint 支持多种配置文件格式,按优先级顺序如下:
.eslintrc.js- JavaScript 文件.eslintrc.cjs- CommonJS 模块.eslintrc.yaml- YAML 文件.eslintrc.yml- YAML 文件.eslintrc.json- JSON 文件package.json中的eslintConfig字段
JavaScript 配置文件
javascript
// .eslintrc.js
module.exports = {
// 环境定义
env: {
browser: true, // 启用浏览器全局变量
es2021: true, // 启用 ES2021 功能
node: true, // 启用 Node.js 全局变量
jest: true, // 启用 Jest 全局变量
mocha: true, // 启用 Mocha 全局变量
commonjs: true // 启用 CommonJS 全局变量
},
// 解析器选项
parser: '@typescript-eslint/parser', // 使用 TypeScript 解析器
parserOptions: {
ecmaVersion: 2021, // ES 版本
sourceType: 'module', // 模块类型: 'script' 或 'module'
ecmaFeatures: {
jsx: true, // 启用 JSX
globalReturn: false, // 不允许在非函数代码块中使用 return
impliedStrict: true, // 启用全局严格模式
experimentalObjectRestSpread: true // 启用实验性对象展开语法
}
},
// 继承的配置
extends: [
'eslint:recommended', // ESLint 推荐规则
'@typescript-eslint/recommended', // TypeScript 推荐规则
'plugin:react/recommended', // React 推荐规则
'plugin:import/errors', // Import 错误规则
'plugin:import/warnings', // Import 警告规则
'prettier' // Prettier 配置(关闭冲突规则)
],
// 使用的插件
plugins: [
'react', // React 插件
'import', // Import 插件
'@typescript-eslint', // TypeScript 插件
'jsx-a11y' // 可访问性插件
],
// 具体规则配置
rules: {
'no-console': 'warn', // 禁止 console,警告级别
'no-debugger': 'error', // 禁止 debugger,错误级别
'semi': ['error', 'always'], // 要求使用分号
'quotes': ['error', 'single'], // 要求使用单引号
'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'
}
}
]
};
YAML 配置文件
yaml
# .eslintrc.yaml
env:
browser: true
es2021: true
node: true
extends:
- eslint:recommended
parserOptions:
ecmaVersion: 12
sourceType: module
rules:
no-console: warn
no-debugger: error
semi:
- error
- always
quotes:
- error
- single
comma-dangle:
- error
- never
overrides:
- files: ["**/*.test.js"]
env:
jest: true
rules:
no-unused-expressions: off
JSON 配置文件
json
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": [
"eslint:recommended"
],
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"no-console": "warn",
"no-debugger": "error",
"semi": ["error", "always"],
"quotes": ["error", "single"],
"comma-dangle": ["error", "never"]
}
}
package.json 配置
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 推荐配置
javascript
module.exports = {
extends: [
'eslint:recommended' // ESLint 官方推荐配置
]
};
使用第三方配置
javascript
module.exports = {
extends: [
'airbnb', // Airbnb 风格
'standard', // Standard 风格
'google', // Google 风格
'prettier' // Prettier 配置
]
};
使用插件配置
javascript
module.exports = {
extends: [
'plugin:react/recommended', // React 推荐配置
'plugin:import/errors', // Import 错误配置
'plugin:import/warnings', // Import 警告配置
'@typescript-eslint/recommended' // TypeScript 推荐配置
]
};
配置文件解析规则
配置文件查找
ESLint 会从目标文件所在目录开始向上查找配置文件:
project/
├── .eslintrc.js # 根配置
├── src/
│ ├── .eslintrc.js # 覆盖配置
│ └── components/
│ └── Button.js # 使用 src/ 目录的配置
└── tests/
└── .eslintrc.js # 测试专用配置
配置文件优先级
ESLint 遵循以下优先级顺序:
- 内联注释(
/* eslint-disable */) - 文件级配置(
/* eslint */) - 目录级配置文件
- 父目录配置文件
- 命令行参数
环境配置详解
预定义环境
javascript
module.exports = {
env: {
// 浏览器环境
browser: true,
// Node.js 环境
node: true,
// ES6 环境
es6: true,
// CommonJS 环境
commonjs: true,
// AMD 环境
amd: true,
// Jest 环境
jest: true,
// Mocha 环境
mocha: true,
// Jasmine 环境
jasmine: true,
// jQuery 环境
jquery: true,
// Prototype.js 环境
prototypejs: true,
// ShellJS 环境
shelljs: true,
// Web Workers 环境
worker: true,
// 非严格模式
non-strict: true,
// 严格模式
strict: true,
// Ember 环境
ember: true,
// Web Extensions 环境
webextensions: true,
// GreaseMonkey 环境
greasemonkey: true
}
};
解析器配置详解
常用解析器
javascript
module.exports = {
// 默认解析器
parser: 'espree',
// Babel 解析器
parser: '@babel/eslint-parser',
// TypeScript 解析器
parser: '@typescript-eslint/parser',
// 解析器选项
parserOptions: {
ecmaVersion: 2021, // ES 版本 (3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023)
sourceType: 'module', // 源码类型 ('script' 或 'module')
ecmaFeatures: {
jsx: true, // 启用 JSX
globalReturn: false, // 允许在全局作用域返回
impliedStrict: true, // 启用全局严格模式
experimentalObjectRestSpread: true // 实验性对象展开语法
}
}
};
Babel 解析器配置
javascript
module.exports = {
parser: '@babel/eslint-parser',
parserOptions: {
requireConfigFile: false, // 不需要 babel 配置文件
babelOptions: {
presets: [
'@babel/preset-env',
'@babel/preset-react'
],
plugins: [
'@babel/plugin-proposal-class-properties',
'@babel/plugin-proposal-object-rest-spread'
]
},
ecmaVersion: 2021,
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
}
};
TypeScript 解析器配置
javascript
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2021,
sourceType: 'module',
ecmaFeatures: {
jsx: true
},
// TypeScript 特定选项
project: './tsconfig.json', // 指定 tsconfig.json 路径
tsconfigRootDir: __dirname, // tsconfig.json 的根目录
warnOnUnsupportedTypeScriptVersion: true
}
};
覆盖配置详解
基本覆盖配置
javascript
module.exports = {
rules: {
'no-console': 'error'
},
overrides: [
{
// 指定文件模式
files: ['*.test.js', '*.spec.js'],
// 为这些文件设置环境
env: {
jest: true
},
// 为这些文件设置规则
rules: {
'no-console': 'off', // 测试文件中允许 console
'jest/expect-expect': 'off' // 测试文件中不要求 expect
}
}
]
};
高级覆盖配置
javascript
module.exports = {
// 通用配置
rules: {
'no-console': 'error',
'no-unused-vars': 'error'
},
overrides: [
// 测试文件配置
{
files: ['**/*.test.*', '**/*.spec.*', '**/test/**', '**/tests/**'],
env: {
jest: true,
'jest/globals': true
},
plugins: ['jest'],
extends: ['plugin:jest/recommended'],
rules: {
'no-console': 'off',
'no-unused-vars': 'off',
'jest/expect-expect': 'off'
}
},
// 配置文件配置
{
files: ['*.config.*', '*.conf.*', '.*rc.*'],
env: {
node: true
},
rules: {
'no-console': 'off',
'no-process-env': 'off'
}
},
// TypeScript 文件配置
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: ['@typescript-eslint/recommended'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { 'argsIgnorePattern': '^_' }]
}
},
// React 文件配置
{
files: ['*.jsx', '*.tsx'],
parserOptions: {
ecmaFeatures: {
jsx: true
}
},
plugins: ['react'],
extends: ['plugin:react/recommended'],
rules: {
'react/react-in-jsx-scope': 'off' // React 17+ 不需要
}
}
]
};
全局变量配置
全局变量类型
javascript
module.exports = {
globals: {
// 只读变量(不能被赋值)
myReadonlyGlobal: 'readonly',
// 可写变量(可以被赋值)
myWritableGlobal: 'writable',
// 禁用变量(视为未定义)
myDisabledGlobal: 'off',
// 与 'readonly' 等价
myConstGlobal: 'readonly',
// 与 'writable' 等价
myVarGlobal: 'writable'
}
};
插件配置详解
基本插件配置
javascript
module.exports = {
plugins: [
'react', // 启用 eslint-plugin-react
'import', // 启用 eslint-plugin-import
'@typescript-eslint', // 启用 @typescript-eslint/eslint-plugin
'jsx-a11y' // 启用 eslint-plugin-jsx-a11y
],
// 使用插件规则
rules: {
'react/jsx-uses-react': 'error',
'import/no-unresolved': 'error',
'@typescript-eslint/explicit-function-return-type': 'warn'
}
};
插件设置
javascript
module.exports = {
plugins: [
'react',
'import'
],
settings: {
// React 设置
react: {
version: 'detect', // 自动检测 React 版本
flowVersion: '0.53', // Flow 版本
pragma: 'React', // React 命名空间
fragment: 'Fragment' // Fragment 组件名
},
// Import 设置
'import/resolver': {
// 模块解析器配置
node: {
paths: ['src'], // 解析路径
extensions: ['.js', '.jsx', '.ts', '.tsx'] // 扩展名
}
},
// Import 外部模块
'import/external-module-folders': [
'node_modules',
'node_modules/@types'
],
// Import 语法
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx']
}
}
};
配置文件最佳实践
项目级配置示例
javascript
// .eslintrc.js - 完整的项目配置示例
module.exports = {
// 环境配置
env: {
browser: true,
es2021: true,
node: true,
jest: true
},
// 解析器配置
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2021,
sourceType: 'module',
ecmaFeatures: {
jsx: true
},
project: './tsconfig.json'
},
// 继承的配置
extends: [
'eslint:recommended',
'@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:import/recommended',
'plugin:import/typescript',
'prettier'
],
// 使用的插件
plugins: [
'react',
'import',
'@typescript-eslint',
'jsx-a11y',
'prettier'
],
// 设置
settings: {
react: {
version: 'detect'
},
'import/resolver': {
typescript: {
project: './tsconfig.json'
}
}
},
// 规则配置
rules: {
'no-console': 'warn',
'no-debugger': 'error',
'semi': ['error', 'always'],
'quotes': ['error', 'single'],
'comma-dangle': ['error', 'never'],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'react/react-in-jsx-scope': 'off',
'react/prop-types': 'off'
},
// 覆盖配置
overrides: [
{
files: ['**/*.test.*', '**/*.spec.*'],
env: {
jest: true
},
rules: {
'no-console': 'off',
'@typescript-eslint/no-explicit-any': 'off'
}
}
]
};
配置文件验证
验证配置文件是否正确:
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"
# 检查特定文件的配置
npx eslint --print-config --env-info
小结
ESLint 配置文件是代码检查的核心,通过合理的配置可以确保代码质量和一致性。了解各种配置选项和最佳实践有助于创建适合项目的 ESLint 配置。