React项目用ESLint禁用useNavigate时插件加载失败的解决方法
解决ESLint找不到自定义插件的问题
问题根源
你自定义了eslint-plugin-no-react-hooks.js插件文件,但ESLint默认会去node_modules目录查找名为eslint-plugin-no-react-hooks的npm包,而非本地文件;同时配置中还存在两处错误:
- 规则前缀拼写错误(
no-react-hook应为no-react-hooks) - 引用了自定义插件未提供的
recommended配置
修复步骤
1. 调整自定义插件文件
在eslint-plugin-no-react-hooks.js中添加name字段,明确插件标识:
module.exports = { name: 'no-react-hooks', // 新增:指定插件名称 rules: { 'use-navigate': { meta: { type: 'problem', docs: { description: 'Prevent usage of the useNavigate hook', category: 'Best Practices', recommended: true, }, }, create(context) { return { ImportDeclaration(node) { if ( node.source.value === 'react-router-dom' && node.specifiers.some( (specifier) => specifier.imported.name === 'useNavigate', ) ) { context.report({ node: node, message: 'Do not use the useNavigate hook. Instead, use "useCustomNavigate"', }); } }, }; }, }, }, };
2. 重构ESLint配置文件
将.eslintrc.json改为.eslintrc.js(JSON无法处理本地文件路径解析),并修正配置内容:
module.exports = { extends: [ "react-app" // 移除:自定义插件未提供recommended配置,无需引用 ], plugins: [ "react", require.resolve("./eslint-plugin-no-react-hooks.js") // 直接引入本地插件文件 ], rules: { "no-react-hooks/use-navigate": "error" // 修正规则前缀拼写 } };
3. 验证修复
运行ESLint命令,此时插件会被正确加载,一旦检测到useNavigate的导入,就会抛出错误提示。
内容的提问来源于stack exchange,提问作者David Johns
相关产品推荐
相关产品推荐

