You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目用ESLint禁用useNavigate时插件加载失败的解决方法

解决ESLint找不到自定义插件的问题

问题根源

你自定义了eslint-plugin-no-react-hooks.js插件文件,但ESLint默认会去node_modules目录查找名为eslint-plugin-no-react-hooks的npm包,而非本地文件;同时配置中还存在两处错误:

  1. 规则前缀拼写错误(no-react-hook应为no-react-hooks)
  2. 引用了自定义插件未提供的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:02:32