ESLint规则示例代码:为每个规则提供典型的使用示例
引言
还在为ESLint规则配置而头疼?不知道如何正确使用各种规则?本文将为你提供ESLint核心规则的详细示例代码,涵盖错误用法、正确用法以及配置选项,帮助你彻底掌握ESLint规则的使用技巧。
读完本文,你将获得:
- ✅ 20+个常用ESLint规则的完整示例
- ✅ 每种规则的错误和正确用法对比
- ✅ 详细的配置选项说明
- ✅ 实用的代码修复建议
- ✅ 规则分类和使用场景指南
ESLint规则分类体系
核心规则详解与示例
1. 变量相关规则
no-unused-vars - 禁止未使用变量
规则说明:检测声明但未使用的变量,帮助清理代码冗余。
// ❌ 错误示例
function calculateSum(a, b) {
const unusedVar = 10; // 未使用的变量
return a + b;
}
const unusedGlobal = 42; // 未使用的全局变量
// ✅ 正确示例
function calculateSum(a, b) {
return a + b;
}
// 配置选项示例
module.exports = {
rules: {
'no-unused-vars': ['error', {
vars: 'all', // 检查所有变量
args: 'after-used', // 参数在使用后检查
ignoreRestSiblings: true // 忽略rest操作符的兄弟
}]
}
};
prefer-const - 优先使用const
规则说明:强制使用const声明不会被重新赋值的变量。
// ❌ 错误示例
let pi = 3.14; // 不会被重新赋值
let config = { port: 3000 };
// ✅ 正确示例
const pi = 3.14;
const config = { port: 3000 };
// 允许重新赋值的特殊情况
let counter = 0;
counter = 1; // 允许重新赋值
2. 相等性检查规则
eqeqeq - 强制使用严格相等
规则说明:要求使用===和!==而不是==和!=。
// ❌ 错误示例
if (value == null) { /* ... */ }
if (count != 0) { /* ... */ }
// ✅ 正确示例
if (value === null || value === undefined) { /* ... */ }
if (count !== 0) { /* ... */ }
// 智能模式配置
module.exports = {
rules: {
'eqeqeq': ['error', 'smart', { null: 'ignore' }]
}
};
// 智能模式下的特殊情况
if (typeof value == 'string') { // 允许,因为typeof总是返回字符串
if (value == null) { // 允许,检查null或undefined
}
3. 控制台相关规则
no-console - 限制console使用
规则说明:禁止或限制console语句的使用,通常用于生产环境。
// ❌ 错误示例
console.log('Debug info');
console.error('Error occurred');
// ✅ 正确示例
// 生产环境中完全禁用console
// 或者使用日志库代替
// 配置允许特定的console方法
module.exports = {
rules: {
'no-console': ['error', { allow: ['warn', 'error'] }]
}
};
// 允许的用法
console.warn('警告信息');
console.error('错误信息');
4. 代码风格规则
indent - 代码缩进
规则说明:强制统一的代码缩进风格。
// ❌ 错误示例(混合缩进)
function badIndent() {
const x = 1; // 2空格
const y = 2; // 4空格
}
// ✅ 正确示例(一致的2空格缩进)
function goodIndent() {
const x = 1;
const y = 2;
if (x > y) {
return x;
}
}
// 配置选项
module.exports = {
rules: {
'indent': ['error', 2, {
SwitchCase: 1, // switch case缩进
VariableDeclarator: { var: 2, let: 2, const: 2 }
}]
}
};
quotes - 引号使用
规则说明:统一字符串引号的使用。
// ❌ 错误示例(混合引号)
const name = "John";
const message = 'Hello world';
// ✅ 正确示例(一致的单引号)
const name = 'John';
const message = 'Hello world';
// 或者一致的双引号
const name = "John";
const message = "Hello world";
// 配置模板字符串
const greeting = `Hello ${name}`; // 允许模板字符串
// 配置选项
module.exports = {
rules: {
'quotes': ['error', 'single', {
avoidEscape: true, // 允许转义
allowTemplateLiterals: true // 允许模板字符串
}]
}
};
5. 箭头函数规则
arrow-body-style - 箭头函数体风格
规则说明:统一箭头函数体的书写风格。
// ❌ 错误示例(不一致的风格)
const add = (a, b) => {
return a + b;
};
const multiply = (a, b) => a * b;
// ✅ 正确示例(隐式返回)
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
// ✅ 正确示例(显式返回块)
const complexOperation = (a, b) => {
const result = a + b;
return result * 2;
};
// 配置选项
module.exports = {
rules: {
'arrow-body-style': ['error', 'as-needed', {
requireReturnForObjectLiteral: false
}]
}
};
6. 导入导出规则
no-unused-imports - 禁止未使用的导入
规则说明:检测并删除未使用的导入语句。
// ❌ 错误示例
import React from 'react'; // 未使用
import { useState } from 'react'; // 未使用
import lodash from 'lodash'; // 未使用
function Component() {
return <div>Hello</div>;
}
// ✅ 正确示例
import React from 'react';
function Component() {
return <div>Hello</div>;
}
// 类型导入的特殊处理
import type { User } from './types'; // TypeScript类型导入
规则配置最佳实践表
| 规则类别 | 推荐规则 | 配置建议 | 使用场景 |
|---|---|---|---|
| 变量管理 | no-unused-vars | {vars: 'all', args: 'after-used'} | 所有项目 |
| 类型安全 | eqeqeq | 'smart' 模式 | 所有项目 |
| 代码质量 | no-console | 生产环境:'error',开发环境:'warn' | 按环境配置 |
| 代码风格 | indent | 2 空格缩进 | 团队统一 |
| ES6+特性 | prefer-const | 默认配置 | 现代项目 |
| 异步代码 | no-await-in-loop | 根据业务需求配置 | 性能敏感项目 |
高级配置示例
组合规则配置
// .eslintrc.js 完整配置示例
module.exports = {
env: {
es2021: true,
node: true,
browser: true
},
extends: ['eslint:recommended'],
rules: {
// 变量相关
'no-unused-vars': ['error', {
vars: 'all',
args: 'after-used',
ignoreRestSiblings: true
}],
'prefer-const': 'error',
// 类型安全
'eqeqeq': ['error', 'smart'],
// 代码风格
'indent': ['error', 2, { SwitchCase: 1 }],
'quotes': ['error', 'single', { avoidEscape: true }],
'semi': ['error', 'always'],
// 最佳实践
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
'curly': 'error',
'dot-notation': 'error'
}
};
规则优先级配置
常见问题解决方案
问题1:误报未使用变量
场景:框架自动使用的变量被标记为未使用
// React组件props误报
function MyComponent({ prop1, prop2 }) { // prop2可能被误报
return <div>{prop1}</div>;
}
// 解决方案:配置忽略模式
module.exports = {
rules: {
'no-unused-vars': ['error', {
varsIgnorePattern: '^_', // 忽略以_开头的变量
argsIgnorePattern: '^_' // 忽略以_开头的参数
}]
}
};
// 使用忽略模式
function MyComponent({ prop1, _prop2 }) { // _prop2不会被检查
return <div>{prop1}</div>;
}
问题2:第三方库的特殊处理
场景:全局变量或特定库的特殊规则
// 配置全局变量
module.exports = {
env: {
jquery: true // 识别$为全局变量
},
globals: {
React: 'readonly',
process: 'readonly'
},
rules: {
'no-undef': 'error' // 检查未定义变量
}
};
总结
通过本文的详细示例和最佳实践,你应该已经掌握了ESLint核心规则的使用方法。记住这些关键点:
- 循序渐进:从基本规则开始,逐步添加更严格的规则
- 团队统一:确保团队使用相同的规则配置
- 环境区分:为开发和生产环境配置不同的严格程度
- 定期审查:定期检查规则配置,确保其符合项目需求
ESLint的强大之处在于它的可配置性和扩展性,正确使用这些规则将显著提升你的代码质量和开发效率。
下一步行动:
- 根据项目需求选择适合的规则子集
- 配置预提交钩子自动运行ESLint
- 定期更新ESLint版本和规则配置
- 考虑使用ESLint插件扩展功能
开始行动吧,让你的代码更加规范、健壮和可维护!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



