关于 eslint
ESLint 是用于 JavaScript 和 TypeScript 项目的代码检查技能,可配置规则、检查代码并自动修复部分问题。内容涵盖常见项目配置与命令行操作。
主要功能
- 01配置扁平格式规则
- 02检查 JavaScript 和 TypeScript
- 03自动修复可处理的问题
- 04设置文件匹配与忽略项
- 05使用共享配置
适用场景
- 01为新项目配置代码检查
- 02发布前检查源文件
- 03自动修复代码风格问题
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ el-feo/ ai-context --skill eslint安装后在 Claude Code 中输入/eslint确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/.eslintignore.exampleeslint.config.examples.jsreferences/custom_rules.mdintegration.mdmigration_guide.mdrule_reference.mdtype_aware_linting.md详细介绍
ESLint
快速入门
前提条件
- 支持 SSL 的 Node.js(^18.18.0、^20.9.0 或 >=21.1.0)
- 已有
package.json文件(如有需要,运行npm init)
安装与设置
自动设置(推荐):
npm init @eslint/config@latest
此交互式设置会询问有关项目的问题,并创建 eslint.config.js 文件。
手动设置:
# Install ESLint packages
npm install --save-dev eslint@latest @eslint/js@latest
# Create configuration file
touch eslint.config.js
基本配置
新版扁平配置格式(ESLint 9.0+)使用 eslint.config.js:
import { defineConfig } from "eslint/config";
import js from "@eslint/js";
export default defineConfig([
{
files: ["**/*.js"],
plugins: { js },
extends: ["js/recommended"],
rules: {
"no-unused-vars": "warn",
"no-undef": "warn"
}
}
]);
运行 ESLint
# Lint a single file
npx eslint yourfile.js
# Lint a directory
npx eslint src/
# Lint with auto-fix
npx eslint src/ --fix
ESLint 核心任务
1. 设置 ESLint
JavaScript 项目
npm init @eslint/config@latest
选择选项:
- 你希望如何使用 ESLint?→ 检查语法、发现问题并强制执行代码风格
- 使用哪种模块类型?→ JavaScript 模块(import/export)
- 使用哪个框架?→ None/React/Vue(视情况而定)
- 项目是否使用 TypeScript?→ No
- 代码运行在哪里?→ Browser 和/或 Node
- 配置文件格式 → JavaScript/JSON/YAML(推荐 JavaScript)
TypeScript 项目
npm install --save-dev eslint@latest @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript-eslint
TypeScript 配置:
import { defineConfig } from 'eslint/config';
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
export default defineConfig(
eslint.configs.recommended,
...tseslint.configs.recommended
);
React + TypeScript
npm install --save-dev \
eslint \
@typescript-eslint/parser \
@typescript-eslint/eslint-plugin \
eslint-plugin-react \
eslint-plugin-react-hooks \
eslint-plugin-jsx-a11y \
typescript-eslint
2. 配置规则
规则严重级别
"off"或0- 禁用规则"warn"或1- 警告(不影响退出代码)"error"或2- 错误(退出代码将为 1)
常见规则配置
基本规则:
export default defineConfig([
{
rules: {
// Enforce semicolons
"semi": ["error", "always"],
// Enforce const where possible
"prefer-const": "error",
// Warn on unused variables
"no-unused-vars": "warn",
// No console.log in production
"no-console": ["error", { allow: ["warn", "error"] }],
// Enforce consistent quotes
"quotes": ["error", "single"],
// Require === instead of ==
"eqeqeq": ["error", "always"]
}
}
]);
TypeScript 专用规则:
export default defineConfig([
{
files: ["**/*.ts", "**/*.tsx"],
rules: {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/explicit-function-return-type": ["error", {
allowExpressions: true
}],
"@typescript-eslint/naming-convention": ["error", {
selector: "interface",
format: ["PascalCase"],
custom: {
regex: "^I[A-Z]",
match: false
}
}]
}
}
]);
配置注释
在行内禁用规则:
/* eslint-disable no-console */
console.log('This is allowed');
/* eslint-enable no-console */
// Disable for single line
console.log('Debug'); // eslint-disable-line no-console
// Disable next line
// eslint-disable-next-line no-console
console.log('Debug');
// Disable specific rules
alert('foo'); // eslint-disable-line no-alert, no-undef
行内禁用的最佳实践:
-
谨慎使用,并给出明确理由
-
说明原因:
// eslint-disable-next-line no-console -- Debugging production issue #1234 console.log('User data:', userData); -
优先修改配置文件,而非行内禁用
-
为临时禁用创建后续任务
3. 文件模式与忽略项
指定要检查的文件
export default defineConfig([
{
// Only lint TypeScript files in src/
files: ["src/**/*.ts", "src/**/*.tsx"],
// Ignore test files for certain rules
ignores: ["**/*.test.ts", "**/*.spec.ts"]
}
]);
全局忽略项
export default defineConfig([
{
ignores: [
"**/node_modules/**",
"**/dist/**",
"**/build/**",
"**/.next/**",
"**/coverage/**"
]
},
// ... rest of config
]);
4. 使用共享配置
ESLint 支持扩展常用配置:
import { defineConfig } from "eslint/config";
import js from "@eslint/js";
import globals from "globals";
export default defineConfig([
js.configs.recommended, // ESLint recommended rules
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
}
]);
常用共享配置:
eslint:recommended- ESLint 推荐规则@typescript-eslint/recommended- TypeScript 推荐规则@typescript-eslint/strict- 更严格的 TypeScript 规则plugin:react/recommended- React 最佳实践plugin:react-hooks/recommended- React Hooks 规则
5. 自动修复问题
ESLint 可以自动修复许多问题:
# Fix all auto-fixable issues
npx eslint src/ --fix
# Show what would be fixed (dry run)
npx eslint src/ --fix-dry-run
可自动修复的规则包括:
- 格式问题(空格、分号、引号)
- 简单的代码转换(prefer-const、箭头函数)
- 导入排序
无法自动修复的问题需要手动处理:
- 逻辑错误(实际使用了 no-unused-vars)
- 复杂的重构需求
常见项目场景
React + TypeScript 项目
完整配置:
import { defineConfig } from 'eslint/config';
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
export default defineConfig([
{ ignores: ['dist'] },
js.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
project: './tsconfig.json'
}
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true }
],
'@typescript-eslint/no-unused-vars': ['error', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_'
}]
}
}
]);
Node.js + TypeScript 项目
import { defineConfig } from 'eslint/config';
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import globals from 'globals';
export default defineConfig([
eslint.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.ts'],
languageOptions: {
globals: globals.node
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'no-console': 'off' // Console is fine in Node.js
}
}
]);
Monorepo 配置
export default defineConfig([
// Global ignores
{ ignores: ['**/dist/**', '**/build/**'] },
// Frontend package
{
files: ['packages/frontend/**/*.{ts,tsx}'],
languageOptions: {
globals: globals.browser
},
// Frontend-specific rules
},
// Backend package
{
files: ['packages/backend/**/*.ts'],
languageOptions: {
globals: globals.node
},
// Backend-specific rules
}
]);
集成
有关 VS Code 设置、CI/CD(GitHub Actions)、提交前钩子(Husky/lint-staged)和 package.json 脚本,请参阅 references/integration.md。
故障排除
常见问题
“Cannot find module 'eslint/config'”
- 更新至 ESLint 9.0+:
npm install eslint@latest
“Parsing error: Cannot find module '@typescript-eslint/parser'”
- 安装解析器:
npm install --save-dev @typescript-eslint/parser
规则未生效
- 检查文件模式是否匹配源文件
- 确认配置文件名称正确(
eslint.config.js) - 确保配置文件位于项目根目录
大型项目中检查速度慢
- 为 node_modules、dist、build 文件夹添加适当的忽略项
- 使用
--cache标记:npx eslint --cache . - 考虑使用
--max-warnings 0,以便在 CI 中遇到警告时失败
高级主题
创建自定义规则
有关项目专用模式,请参阅 references/custom_rules.md。
TypeScript 类型感知检查
有关需要类型信息的高级 TypeScript 检查,请参阅 references/type_aware_linting.md。
规则参考
如需查看包含示例的完整规则参考,请参阅 references/rule_reference.md。
从 ESLint 8.x 迁移
对于使用旧版 .eslintrc.* 格式的项目,请参阅 references/migration_guide.md。