Task: I'm trying to use React.lazy function for dynamic loading of React components.
Problem: I get the following ESLint warning:
ESLint: Fast refresh only works when a file only exports components. Move your component(s) to a separate file.(react-refresh/only-export-components)
Main technologies:
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.2",
"vite": "^4.4.0",
Example code:
// 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};
What I've tried:
Change the default export of the ErrorPage to the named export. And then to refactor the loading of this one to the router module like that:
// 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};
P.S: The lazy loading works, but I just wanna know how to avoid this warning.
As per this (currently) open issue on the eslint-plugin-react-refresh project, this is most likely a false positive.
The author of the project suggests these work-arounds
There are two solutions:
- Put a disable comment for this rule for all the file. This will not actually break fast refresh so this ok>
- Instead of exporting the router, export a component that render the Router provider
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With