如何避免 React 中的 ESLint 警告:快速刷新仅在文件仅导出组件时有效?

Вла*_*ров 6 lazy-loading reactjs eslint

任务: 我正在尝试使用 React.lazy 函数来动态加载 React 组件。

问题: 我收到以下 ESLint 警告:

ESLint:快速刷新仅在文件仅导出组件时有效。将您的组件移动到单独的文件中。(react-refresh/only-export-components)

主要技术:
“react”:“^18.2.0”,
“react-dom”:“^18.2.0”,
“react-router-dom”:“^6.14.2”,
“vite”:“^4.4”。 0”,

示例代码:

// ErrorPage.tsx file for React.lazy:
import {FC} from "react";

const ErrorPage: FC = () => {
    return (
        <section className="error-page">
            <h1>Not found</h1>
        </section>
    );
};

export default ErrorPage;



// router file with React.lazy function:
import {createBrowserRouter} from "react-router-dom";
import {lazy} from "react";
import IndexPage from "../pages/Index.tsx";

// The next line gives the above-mentioned warning
const ErrorPage = lazy(() => import("../pages/404/ErrorPage.tsx"));

const router = createBrowserRouter([
    {
        element: <IndexPage/>,
        path: "/",
        children: [
            // ... other pages ...
            {
                path: "*",
                element: <ErrorPage/>
            }
        ]
    }
]);

export {router};
Run Code Online (Sandbox Code Playgroud)

我尝试过的方法:
将 ErrorPage 的默认导出更改为命名导出。然后将其加载重构为路由器模块,如下所示:

// router file with React.lazy function:
import {createBrowserRouter} from "react-router-dom";
import {lazy} from "react";
import IndexPage from "../pages/Index.tsx";

// I still get the ESLint warning
const ErrorPage = lazy(() =>
    import("../pages/404/ErrorPage.tsx")
        .then(({ErrorPage}) => ({default: ErrorPage}))
);

const router = createBrowserRouter([
    {
        element: <IndexPage/>,
        path: "/",
        children: [
            // ... other pages ...
            {
                path: "*",
                element: <ErrorPage/>
            }
        ]
    }
]);

export {router};
Run Code Online (Sandbox Code Playgroud)

PS:延迟加载是有效的,但我只是想知道如何避免这个警告。

Phi*_*hil 1

根据eslint-plugin-react-refresh 项目(当前)未解决的问题,这很可能是误报。

该项目的作者建议这些解决方法

有两种解决方案:

  • 为所有文件添加此规则的禁用注释。这实际上不会破坏快速刷新,所以这可以>
  • 不要导出路由器,而是导出呈现路由器提供程序的组件