如何让新格式ESLint配置与pre-commit正常工作?
问题核心
pre-commit的mirrors-eslint钩子在使用新格式eslint.config.js时,Node.js无法找到globals等依赖包,但旧格式.eslintrc.json正常工作。原因是新配置采用ES模块语法(import/export)时,Node.js的模块解析路径未包含pre-commit缓存中的依赖目录,而旧JSON配置由ESLint内部处理依赖查找,不受此限制。
调试步骤
确认依赖已安装
进入pre-commit的ESLint钩子缓存目录(路径类似~/.cache/pre-commit/repos/[随机哈希值]/node_modules),检查globals、@eslint/js、eslint-config-prettier是否存在。可通过pre-commit clean && pre-commit install-hooks重新安装依赖后查找。手动验证ESLint配置
直接使用缓存中的ESLint二进制文件测试配置:~/.cache/pre-commit/repos/[哈希值]/node_modules/.bin/eslint .如果同样报错,说明是Node模块路径问题;如果正常,说明是pre-commit运行钩子时的环境变量缺失。
检查钩子运行环境
在pre-commit钩子配置中添加verbose: true,运行pre-commit run --all-files,查看输出的环境变量,确认NODE_PATH是否包含依赖所在的node_modules目录。
解决方案
方案1:注入NODE_PATH环境变量
在pre-commit的ESLint钩子配置中,添加env字段指定Node模块查找路径:
- repo: https://github.com/pre-commit/mirrors-eslint rev: v8.51.0 hooks: - id: eslint types: [javascript] env: # 指向pre-commit缓存中的依赖目录 NODE_PATH: "{{ pre_commit_home }}/repos/{{ repo_hash }}/node_modules" additional_dependencies: [ 'globals@13.21.0', 'eslint@8.51.0', '@eslint/js', 'eslint-config-prettier@9.0.0' ]
pre-commit会自动替换{{ pre_commit_home }}和{{ repo_hash }}为实际路径,确保Node.js能找到依赖。
方案2:改用CommonJS格式的配置文件
将eslint.config.js改为CommonJS语法(兼容Node.js的require机制),避免ES模块的路径解析问题:
const globals = require("globals"); const js = require("@eslint/js"); const eslintConfigPrettier = require("eslint-config-prettier"); module.exports = [ js.configs.recommended, eslintConfigPrettier, { languageOptions: { globals: { ...globals.browser, }, sourceType: "module", ecmaVersion: 2022, }, }, { ignores: ["project/static/htmx/**"], }, ];
方案3:确认Node.js版本兼容性
ESLint 8.51.0要求Node.js版本≥12.22.0,检查pre-commit使用的Node版本:
pre-commit run eslint --verbose | grep "Node.js"
如果版本过低,需升级Node.js或调整pre-commit使用的Node环境。
内容的提问来源于stack exchange,提问作者JK Laiho

