Loading too many routing files at one time will make the first loading speed very slow. It is recommended to
create a new folder routers
common.ts in the form of lazy loading as follows:
import {
lazy } from 'react';
const productRouters: object[] = [
{
path: '/list',
component: lazy(() => import('@/pages/List/index')),
},
{
path: '/detail',
component: lazy(() => import('@/pages/Detail/index')),
},
];
export default productRouters;
Use vite's import.meta.globEager() in index.ts to automatically import files
const autoLoadRoutes: any = [];
const routerFiles = import.meta.globEager('./*.ts');
console.log(routerFiles,'routerFiles')
const paths = Object.keys(routerFiles);
console.log(paths,'paths')
paths.forEach((path) => {
console.log(path,'path')
autoLoadRoutes.push(...routerFiles[path].default);
});
const routes = [
...autoLoadRoutes,
{
path: '*',
component: () => import('@/pages/NotFound'),
},
];
export default routes;
The console can see that it will automatically import the two files we created under the routers folder, traverse to get the address and put it in autoLoadRoutes,
and finally wrap the Switch with Suspense in the APP
import {
Suspense } from 'react';
<Suspense fallback={
<div />}>
<Switch>
{
routes.map((route: any) => (
<Route path={
route.path} key={
route.path} component={
route.component} />
))}
</Switch>
</Suspense>