如何在Gatsby项目中启用react-hooks/exhaustive-deps警告
Gatsby项目开启react-hooks/exhaustive-deps警告的配置方案
配置不生效的核心原因
Gatsby 框架自带内置 ESLint 检查流程,gatsby develop、gatsby build 过程中触发的代码校验默认不会自动读取项目根目录下自定义的 .eslintrc 配置,手动在独立 eslint 配置文件中添加的插件、规则不会被框架的内置校验流程加载,因此普通 React 项目的配置方式在 Gatsby 中不生效。
生效配置步骤
- 确认依赖安装
执行命令安装官方 ESLint 插件:npm install eslint-plugin-react-hooks --save-dev # yarn 用户执行对应命令 # yarn add eslint-plugin-react-hooks -D - 注入规则到 Gatsby 内置校验流程
打开项目根目录的gatsby-node.js文件,添加如下 Webpack 配置修改逻辑,将 react-hooks 相关规则注入框架内置的 ESLint 检查中:exports.onCreateWebpackConfig = ({ actions, getConfig }) => { const webpackConfig = getConfig() // 匹配内置的ESLint校验规则 const eslintCheckRule = webpackConfig.module.rules.find(rule => rule.enforce === 'pre' && rule.use?.loader && (rule.use.loader.includes('eslint-loader') || rule.use.loader.includes('eslint-webpack-plugin')) ) if (eslintCheckRule) { eslintCheckRule.use.options = { ...eslintCheckRule.use.options, plugins: [...(eslintCheckRule.use.options.plugins || []), 'react-hooks'], rules: { ...(eslintCheckRule.use.options.rules || {}), 'react-hooks/rules-of-hooks': 'error', 'react-hooks/exhaustive-deps': 'warn' }, // 开启后会自动合并根目录.eslintrc的自定义配置,后续调整规则无需修改本文件 useEslintrc: true } } actions.replaceWebpackConfig(webpackConfig) } - 重启开发服务
停掉当前运行的gatsby develop进程,重新启动服务后,Hook 依赖缺失的代码就会触发黄色警告提示。
可选替代方案
如果不需要开发时实时告警,也可以不修改 gatsby-node.js,直接在根目录 .eslintrc 中写好规则,在 package.json 中添加独立校验脚本:
{ "scripts": { "lint": "eslint src/**/*.{js,jsx,ts,tsx}" } }
执行npm run lint即可手动扫描出所有不符合exhaustive-deps规则的代码。
注意:若项目使用Gatsby v5及以上版本,上述配置逻辑完全兼容,无需额外调整。
内容的提问来源于stack exchange,提问作者A.A
相关产品推荐
相关产品推荐

