ESLint 详细使用说明
一、什么是 ESLint?
ESLint 是一个开源的 JavaScript 代码检查工具,由 Nicholas C. Zakas 于 2013 年创建,核心作用是:
- 检测代码中的语法错误、潜在 Bug(如未定义变量、类型错误);
- 强制统一代码风格(如缩进、引号、分号);
- 自定义代码规范,适配团队开发流程;
- 支持 ES6+、TypeScript、React/Vue 等框架/语法,可扩展、可配置。
二、核心特性
- 可插拔:所有规则都是插件化的,可按需启用/禁用,也可开发自定义规则;
- 可配置:支持多种配置方式(配置文件、注释、命令行),优先级可自定义;
- 自动修复:多数规则支持
--fix自动修复不符合规范的代码; - 多环境支持:适配浏览器、Node.js、ES Module、CommonJS 等运行环境;
- 集成友好:可与 VS Code、Webpack、Git Hooks、CI/CD 等工具无缝集成。
三、安装与初始化
3.1 局部安装(推荐)
适用于单个项目,避免全局版本冲突:
# 初始化 package.json(若未初始化)
npm init -y
# 安装 ESLint 为开发依赖
npm install eslint --save-dev
3.2 全局安装
适用于多项目共用同一 ESLint 版本(不推荐,易导致版本不一致):
npm install eslint -g
3.3 初始化配置文件
ESLint 提供交互式命令生成配置文件(推荐):
# 局部安装时执行
npx eslint --init
# 全局安装时执行
eslint --init
执行后会出现以下交互选项(以 ESLint v8+ 为例):
- 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(检查语法+发现问题+强制代码风格)
- What type of modules does your project use?(模块类型)
- JavaScript modules (import/export)(ES Module)
- CommonJS (require/exports)(Node.js 常用)
- None of these(无)
- Which framework does your project use?(框架)
- React
- Vue.js
- None of these(无)
- Does your project use TypeScript?(是否使用 TypeScript)
- Yes / No
- Where does your code run?(运行环境,可多选)
- Browser(浏览器)
- Node(Node.js)
- How would you like to define a style for your project?(代码风格定义方式)
- Use a popular style guide(使用流行的风格指南)
- Answer questions about your style(自定义风格)
- Inspect your JavaScript file(s)(检查现有文件生成风格)
- Which style guide do you want to follow?(选择流行风格指南)
- What format do you want your config file to be in?(配置文件格式)
- JavaScript(推荐,支持注释和动态逻辑)
- YAML
- JSON
完成后会自动生成配置文件(如 .eslintrc.js),并安装对应的依赖(如 eslint-config-airbnb-base、eslint-plugin-import 等)。
四、核心配置文件详解
ESLint 配置文件支持多种格式,优先级:.eslintrc.js > .eslintrc.yaml > .eslintrc.yml > .eslintrc.json > package.json 中的 eslintConfig 字段。
以下是 .eslintrc.js 完整示例(注释版):
module.exports = {
// 1. 环境配置:指定代码运行的环境,每个环境会预设对应的全局变量
env: {
browser: true, // 浏览器环境(window、document 等)
es2021: true, // ES2021 语法支持
node: true, // Node.js 环境(require、module 等)
},
// 2. 扩展配置:继承已有的规则集(可继承多个,数组形式)
extends: [
// 基础规则集:ESLint 内置推荐规则
"eslint:recommended",
// 第三方规则集(如 Airbnb 风格)
"airbnb-base",
// 框架/插件规则集(如 React)
// 'plugin:react/recommended'
],
// 3. 解析器配置:指定解析器(默认 Espree,支持 ES6+;TypeScript 需用 @typescript-eslint/parser)
parser: "@typescript-eslint/parser", // TypeScript 解析器
parserOptions: {
ecmaVersion: "latest", // 支持的 ES 版本(latest 为最新)
sourceType: "module", // 模块类型:module(ES Module)/ script(CommonJS)
ecmaFeatures: {
jsx: true, // 支持 JSX(React 项目需开启)
},
},
// 4. 插件配置:引入第三方插件(插件名可省略 eslint-plugin- 前缀)
plugins: [
"@typescript-eslint", // TypeScript 插件
// 'react' // React 插件
],
// 5. 规则配置:自定义规则(优先级最高,会覆盖 extends 中的规则)
rules: {
// 规则格式:"规则名": [规则级别, 规则选项]
// 规则级别:
// - "off" / 0:禁用规则
// - "warn" / 1:警告(不影响代码运行,仅提示)
// - "error" / 2:错误(触发时会终止 lint 流程)
// 示例 1:禁用 console(生产环境推荐 error,开发环境可 warn/off)
"no-console": process.env.NODE_ENV === "production" ? "error" : "off",
// 示例 2:强制使用单引号(字符串引号)
quotes: ["error", "single"],
// 示例 3:强制使用分号结尾
semi: ["error", "always"],
// 示例 4:缩进为 2 个空格
indent: ["error", 2],
// 示例 5:禁用 var,强制使用 let/const
"no-var": "error",
// 示例 6:TypeScript 自定义规则(需配合 @typescript-eslint 插件)
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
// 示例 7:关闭 Airbnb 风格中禁止使用 for 循环的规则
"no-plusplus": "off",
},
// 6. 全局变量配置:声明全局变量,避免 lint 报错
globals: {
jQuery: "readonly", // 只读(不可修改)
Vue: "writable", // 可写(可修改)
},
// 7. 忽略文件配置:指定不需要 lint 的文件/目录(也可单独创建 .eslintignore 文件)
ignorePatterns: [
"node_modules/", // 忽略 node_modules
"dist/", // 忽略打包产物
"*.config.js", // 忽略配置文件
],
};
五、忽略文件:.eslintignore
与 .gitignore 语法类似,指定不需要 ESLint 检查的文件/目录,示例:
# 忽略 node_modules 目录
node_modules/
# 忽略打包输出目录
dist/
build/
out/
# 忽略所有 .min.js 文件
*.min.js
# 忽略特定文件
webpack.config.js
babel.config.js
# 忽略 src/assets 目录下的所有文件
src/assets/
六、常用命令
6.1 检查指定文件/目录
# 检查单个文件
npx eslint src/index.js
# 检查整个目录
npx eslint src/
# 检查多个目录/文件
npx eslint src/ components/ app.js
6.2 自动修复可修复的问题
# 修复指定文件的可修复问题
npx eslint src/index.js --fix
# 修复整个目录的可修复问题
npx eslint src/ --fix
⚠️ 注意:--fix 仅能修复规则标记为可自动修复的问题(如缩进、引号、分号),语法错误、逻辑问题需手动修复。
6.3 输出检查结果为指定格式
# 输出为 JSON 格式(便于集成到 CI/CD)
npx eslint src/ --format json
# 输出为详细的表格格式
npx eslint src/ --format table
# 输出为代码风格检查报告(带规则说明)
npx eslint src/ --format stylish
6.4 检查并输出错误数量(非 0 退出码)
# 若有 error 级别的问题,命令行返回非 0 码(CI/CD 中可用于阻断流程)
npx eslint src/ --quiet
七、规则详解
7.1 规则分类
ESLint 规则分为三大类:
- 语法检查类:检测语法错误(如
no-undef检测未定义变量、no-unreachable检测不可达代码); - 代码风格类:强制统一风格(如
indent缩进、quotes引号、semi分号); - 最佳实践类:避免潜在问题(如
no-console禁用 console、no-var禁用 var、eqeqeq强制使用 === 而非 ==)。
7.2 常用核心规则
| 规则名 | 说明 | 默认级别 | 可自动修复 |
|---|---|---|---|
no-undef | 禁止使用未定义的变量 | error | 否 |
no-unused-vars | 禁止声明未使用的变量 | warn | 否 |
eqeqeq | 强制使用 ===/!== 而非 ==/!= | warn | 是 |
indent | 强制统一缩进 | error | 是 |
quotes | 强制统一引号(单/双) | error | 是 |
semi | 强制使用/禁用分号结尾 | error | 是 |
no-console | 禁止使用 console | off | 否 |
no-var | 禁止使用 var,强制使用 let/const | error | 是 |
curly | 强制 if/else 等语句使用大括号 | warn | 是 |
max-len | 限制单行代码长度 | warn | 否 |
no-trailing-spaces | 禁止行尾有空格 | warn | 是 |
7.3 规则优先级
- 代码内的注释配置(如
/* eslint-disable no-console */)> - 项目配置文件(
.eslintrc.js)中的rules> - 配置文件中的
extends继承的规则 > - ESLint 内置默认规则。
八、集成与进阶用法
8.1 VS Code 集成(实时检查+自动修复)
- 安装 ESLint 插件:在 VS Code 扩展市场搜索「ESLint」(作者:Dirk Baeumer);
- 配置 VS Code 设置(
settings.json):
{
// 保存时自动修复 ESLint 问题
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
// 启用 ESLint 自动检查
"eslint.enable": true,
// 忽略的文件/目录
"eslint.ignorePatterns": ["**/node_modules/*", "**/dist/*"],
// 支持 TypeScript/JSX
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
]
}
8.2 与 Git Hooks 集成(提交前检查)
使用 husky + lint-staged 实现「提交代码前自动 lint 并修复」:
- 安装依赖:
npm install husky lint-staged --save-dev
- 在
package.json中添加配置:
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "git add"]
}
}
- 初始化 husky 并添加 pre-commit 钩子:
npm run prepare
npx husky add .husky/pre-commit "npx lint-staged"
8.3 与 Webpack 集成
使用 eslint-webpack-plugin 实现打包时 lint 检查:
- 安装依赖:
npm install eslint-webpack-plugin --save-dev
- 在
webpack.config.js中配置:
const ESLintPlugin = require("eslint-webpack-plugin");
module.exports = {
plugins: [
new ESLintPlugin({
context: "src", // 检查的目录
extensions: ["js", "jsx", "ts", "tsx"], // 检查的文件后缀
fix: true, // 自动修复
exclude: "node_modules", // 排除目录
}),
],
};
8.4 TypeScript 适配
- 安装依赖:
npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
- 在
.eslintrc.js中配置:
module.exports = {
parser: "@typescript-eslint/parser", // 指定 TypeScript 解析器
parserOptions: {
project: "./tsconfig.json", // 关联 tsconfig.json
},
plugins: ["@typescript-eslint"], // 引入 TypeScript 插件
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended", // TypeScript 推荐规则
"plugin:@typescript-eslint/recommended-requiring-type-checking", // 需类型检查的规则
],
rules: {
// 自定义 TypeScript 规则
"@typescript-eslint/no-explicit-any": "warn", // 禁止使用 any 类型(警告)
"@typescript-eslint/consistent-type-definitions": ["error", "interface"], // 强制使用 interface 而非 type
},
};
九、常见问题与解决方案
9.1 规则冲突(如 Prettier 与 ESLint 风格冲突)
解决方案:使用 eslint-config-prettier 禁用 ESLint 中与 Prettier 冲突的规则,eslint-plugin-prettier 将 Prettier 作为 ESLint 规则运行:
npm install eslint-config-prettier eslint-plugin-prettier prettier --save-dev
配置 .eslintrc.js:
module.exports = {
extends: [
"eslint:recommended",
"plugin:prettier/recommended", // 集成 Prettier
],
};
9.2 全局变量未声明导致 lint 报错
解决方案:
- 在
.eslintrc.js中配置globals:
globals: {
$: 'readonly', // 声明 jQuery 的 $ 为全局变量
process: 'readonly' // 声明 Node.js 的 process 为全局变量
}
- 或在代码中添加注释:
/* global $:readonly */
$(document).ready(function () {});
9.3 某些文件不需要 lint 检查
解决方案:
- 在
.eslintignore中添加忽略规则; - 或在文件顶部添加注释:
/* eslint-disable */ // 禁用整个文件的 lint 检查
/* eslint-disable no-console */ // 仅禁用 no-console 规则
9.4 ESLint 版本与 Node.js 版本不兼容
解决方案:
- ESLint v8+ 要求 Node.js >= 12.22.0;
- ESLint v9+ 要求 Node.js >= 18.18.0;
- 若无法升级 Node.js,可降级 ESLint:
npm install eslint@7 --save-dev # 安装 ESLint v7(兼容 Node.js 10+)
十、常用插件与配置集
10.1 官方/主流插件
| 插件名 | 适用场景 | 说明 |
|---|---|---|
eslint-plugin-react | React 项目 | React 语法/最佳实践规则 |
eslint-plugin-vue | Vue 项目 | Vue 语法/最佳实践规则 |
@typescript-eslint/eslint-plugin | TypeScript 项目 | TypeScript 专属规则 |
eslint-plugin-import | ES Module 项目 | 检查 import/export 规范 |
eslint-plugin-prettier | 与 Prettier 集成 | 将 Prettier 作为 ESLint 规则 |
eslint-plugin-security | 所有项目 | 检测安全漏洞(如 SQL 注入) |
10.2 主流配置集
| 配置集名称 | 适用场景 | 特点 |
|---|---|---|
eslint:recommended | 所有 JS 项目 | ESLint 内置推荐规则 |
airbnb-base | 通用 JS 项目 | 严格的企业级代码规范 |
standard | 通用 JS 项目 | 无分号、单引号,零配置 |
@typescript-eslint/recommended | TS 项目 | TypeScript 推荐规则 |
plugin:vue/vue3-recommended | Vue3 项目 | Vue3 推荐规则 |
十一、总结
- ESLint 是前端代码质量管控的核心工具,优先使用局部安装+项目级配置;
- 规则配置遵循「最小可用」原则,先继承主流配置集,再自定义调整;
- 结合编辑器自动修复、Git Hooks 提交检查、CI/CD 流程检查,最大化发挥作用;
- 与 Prettier 配合时,需处理规则冲突,优先保证风格统一。
十二、参考资料
- ESLint 官方文档:https://eslint.org/docs/latest/
- @typescript-eslint 文档:https://typescript-eslint.io/
- Airbnb JavaScript 风格指南:https://github.com/airbnb/javascript
- ESLint 规则列表:https://eslint.org/docs/rules/