Как грамотно настроить ESLinter для работы с Node?
Ссылка скопирована
Ошибка:
andrew @ andrew-Extensa-5230 ~/CODE/JS/React/IdeaNick (master) └─ $ ▶ git commit -m "fix eslint-config" ✔ Backed up original state in git stash (ba03fa6) ✔ Hiding unstaged changes to partially staged files... ⚠ Running tasks for staged files... ❯ backend/.lintstagedrc.yml — 2 files ❯ *.{ts,tsx,js} — 2 files ✖ eslint --cache --cache-location ./node_modules/.cache/.eslintcache --fix [FAILED] ◼ prettier --loglevel warn --cache --write ↓ *.{json,yml,scss} — no files ↓ Skipped because of errors from tasks. ↓ Skipped because of errors from tasks. ✔ Reverting to original state because of errors... ✔ Cleaning up temporary files... ✖ eslint --cache --cache-location ./node_modules/.cache/.eslintcache --fix: Oops! Something went wrong! :( ESLint: 9.20.1 ReferenceError: pluginNode is not defined at file:///home/andrew/CODE/JS/React/IdeaNick/backend/eslint.config.js?mtime=1754296162327:9:13 at ModuleJob.run (node:internal/modules/esm/module_job:370:25) at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:665:26) at async loadConfigFile (/home/andrew/CODE/JS/React/IdeaNick/node_modules/.pnpm/eslint@9.20.1/node_modules/eslint/lib/config/config-loader.js:197:21) at async ConfigLoader.calculateConfigArray (/home/andrew/CODE/JS/React/IdeaNick/node_modules/.pnpm/eslint@9.20.1/node_modules/eslint/lib/config/config-loader.js:500:32) (node:16384) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///home/andrew/CODE/JS/React/IdeaNick/backend/eslint.config.js?mtime=1754296162327 is not specified and it doesn't parse as CommonJS. Reparsing as ES module because module syntax was detected. This incurs a performance overhead. To eliminate this warning, add "type": "module" to /home/andrew/CODE/JS/React/IdeaNick/backend/package.json. (Use `node --trace-warnings ...` to show where the warning was created) husky - pre-commit script failed (code 1)
Конфиг:
import baseConfig from '../eslint.config.js' import pluginNode from 'eslint-plugin-node' /** @type {import('eslint').Linter.FlatConfig[]} */ export default [ ...baseConfig, { plugins: { node: pluginNode, }, rules: { 'node/no-process-env': 'error' }, }, { files: ['**/*.{ts,js}'], languageOptions: { parserOptions: { project: './tsconfig.json', }, }, }, { ignores: ['dist', 'node_modules', 'coverage', 'eslint.config.js'], }, ]
Нужно решить такую задачу?
Заказать помощь
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Лучший ответ
1
Другие ответы (0)
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопроскомментарий
Вам также может быть интересно
Pyrogram
Как правильно зарегистрировать юзер бота в Telegram?
1 ответ
печатные-платы
Как заставить запускаться программу M3.exe от компании Hanxing AOI в инспекционной машине на Windows 7 Pro?
1 ответ
VPN
Как правильно настроить vless для Android TV?
1 ответ
Visual Studio Code
Как лучше убрать тень у панели слева в VS Code?
1 ответ

Ошибка на git commit с lint-staged обычно означает, что ESLint запускается не в той конфигурации или пытается линтить файлы, для которых не настроено окружение Node/React. Начинать нужно не с husky, а с отдельного запуска ESLint вручную.
Проверьте:
npx eslint .
Если проект на современном ESLint 9, используется flat config eslint.config.js. Для Node нужно явно указать globals и parser options. Пример базовой конфигурации:
import js from '@eslint/js'; import globals from 'globals'; export default [ js.configs.recommended, { files: ['**/*.js'], languageOptions: { ecmaVersion: 'latest', sourceType: 'module', globals: { ...globals.node, ...globals.browser } } } ];import js from '@eslint/js'; import globals from 'globals'; export default [ js.configs.recommended, { files: ['**/*.js'], languageOptions: { ecmaVersion: 'latest', sourceType: 'module', globals: { ...globals.node, ...globals.browser } } } ];
Если у вас старый .eslintrc, для Node должно быть:
{ "env": { "node": true, "browser": true, "es2021": true }, "extends": ["eslint:recommended"] }{ "env": { "node": true, "browser": true, "es2021": true }, "extends": ["eslint:recommended"] }
С lint-staged лучше запускать ESLint только на подходящих файлах:
{ "lint-staged": { "*.{js,jsx,ts,tsx}": "eslint --fix" } }{ "lint-staged": { "*.{js,jsx,ts,tsx}": "eslint --fix" } }
Если при commit lint-staged прячет unstaged changes, это нормальное поведение. Но если задача падает, он откатывает изменения из stash. Ошибка обычно выше в логе: конкретное правило ESLint, синтаксис или отсутствие конфига.
Порядок действий: сначала npx eslint path/to/file.js, потом npx lint-staged, потом git commit. Не чините husky, пока ESLint отдельно не проходит. Для Node-проекта обязательно задайте globals.node, иначе ESLint будет ругаться на process, require, module, __dirname и другие стандартные Node-переменные.