ESLint
eslint 节点;规则与 flat config。
25 分钟
ESLint
ESLint 是 JavaScript/TypeScript 生态最主流的 静态分析(Lint) 工具——在运行前发现 bug 模式、统一风格、 enforce 最佳实践。团队越大,CI 里 eslint 越不可或缺。
学习目标
- 理解 Lint 与格式化(Prettier)的分工
- 会跑
eslint .并读懂常见报错 - 了解 flat config(
eslint.config.js)新格式
ESLint 做什么
源码 .ts / .tsx
→ AST 解析
→ 规则 plugins(react、typescript、import 等)
→ 报告 error / warning
→ 可选 --fix 自动修复
| 类型 | 示例 |
|---|---|
| 错误模式 | no-unused-vars、hooks 依赖数组 |
| 风格 | 引号、分号(可与 Prettier 分工) |
| 框架规则 | react-hooks/exhaustive-deps |
与 Prettier 分工
- ESLint:逻辑与可维护性(见 ft-prettier)
- Prettier:纯排版(缩进、换行)
- 可用
eslint-config-prettier关掉冲突规则
flat config 示例
ESLint 9+ 推荐 flat config:
// eslint.config.js
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default [
js.configs.recommended,
...tseslint.configs.recommended,
{
plugins: { "react-hooks": reactHooks },
rules: { ...reactHooks.configs.recommended.rules },
},
];
老项目可能仍是 .eslintrc.cjs——迁移时对照官方指南,不要两套并存。
在 React / Next 项目中
- react-essentials:
eslint-plugin-react-hooks防止 Hooks 误用 - nextjs-essentials:
eslint-config-next含 Next 特有规则(如<Image>用法) - typescript-essentials:
typescript-eslint把类型感知规则接进 ESLint
CI 集成
npm run lint # package.json scripts
# CI: lint 失败则 block merge
与 html-css-essentials 单文件相比,工程化项目 是常态。