Настройка ESLint для линтинга JavaScript/TypeScript
ESLint — статический анализатор кода. Ловит ошибки до запуска, обеспечивает консистентность стиля, предотвращает антипаттерны. С версии 9 перешёл на flat config — новый формат конфигурации, который проще читается и быстрее парсится.
Установка
npm install --save-dev eslint @eslint/js typescript-eslint
Для React-проектов дополнительно:
npm install --save-dev eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y
eslint.config.mjs (flat config, ESLint 9+)
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import reactPlugin from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';
export default tseslint.config(
// Базовые правила JS
js.configs.recommended,
// TypeScript
...tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: import.meta.dirname,
},
},
},
// React
{
plugins: {
react: reactPlugin,
'react-hooks': reactHooks,
'jsx-a11y': jsxA11y,
},
settings: {
react: { version: 'detect' },
},
rules: {
...reactPlugin.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
...jsxA11y.configs.recommended.rules,
'react/react-in-jsx-scope': 'off', // React 17+ JSX transform
'react/prop-types': 'off', // используем TypeScript
},
},
// Кастомные правила
{
rules: {
// TypeScript
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'@typescript-eslint/consistent-type-imports': ['error', { prefer: 'type-imports' }],
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/await-thenable': 'error',
// Общие
'no-console': ['warn', { allow: ['warn', 'error'] }],
'prefer-const': 'error',
'no-var': 'error',
},
},
// Игнорируемые файлы
{
ignores: ['dist/**', 'node_modules/**', '*.config.js', 'coverage/**'],
}
);
scripts в package.json
{
"scripts": {
"lint": "eslint src",
"lint:fix": "eslint src --fix",
"lint:ci": "eslint src --max-warnings 0"
}
}
--max-warnings 0 в CI — warnings трактуются как ошибки, пайплайн падает.
Устаревший .eslintrc.json (ESLint 8)
Для проектов на ESLint 8 (старый legacy формат):
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "react-hooks"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended-type-checked",
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
"rules": {
"react/react-in-jsx-scope": "off",
"@typescript-eslint/no-explicit-any": "warn"
}
}
Полезные плагины
eslint-plugin-import — контролирует порядок импортов, запрещает циклические зависимости:
npm install --save-dev eslint-plugin-import eslint-import-resolver-typescript
import importPlugin from 'eslint-plugin-import';
rules: {
'import/order': ['error', {
'groups': ['builtin', 'external', 'internal', 'parent', 'sibling'],
'newlines-between': 'always',
'alphabetize': { 'order': 'asc' },
}],
'import/no-cycle': 'error',
'import/no-unused-modules': 'error',
}
eslint-plugin-unicorn — коллекция опinionated правил:
npm install --save-dev eslint-plugin-unicorn
Включать выборочно — unicorn/recommended агрессивен:
rules: {
'unicorn/filename-case': ['error', { case: 'kebabCase' }],
'unicorn/no-array-for-each': 'error', // предпочитает for...of
'unicorn/prefer-node-protocol': 'error', // import fs from 'node:fs'
}
Интеграция с VS Code
.vscode/settings.json:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"eslint.useFlatConfig": true
}
Производительность
Правила recommendedTypeChecked используют TypeScript Language Service и работают медленнее. Если линтинг занимает больше 30 секунд:
// Отключить type-checked для node_modules и конфигов
{
files: ['*.config.*', 'scripts/**'],
...tseslint.configs.recommended, // без TypeChecked
}
Или использовать eslint-plugin-turbo в монорепозитории для кеширования результатов.
Сроки
Настройка ESLint с нуля для TypeScript/React проекта: 1–3 часа. Добавление в существующий проект с исправлением baseline ошибок: 2–8 часов в зависимости от количества проблем.







