一次性加载太多的路由文件会使首次加载的速度很慢,建议将路由以懒加载的形式
新建文件夹routers
common.ts如下:
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;
在index.ts中使用vite的import.meta.globEager()自动导入文件
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;
控制台可以看到会自动导入我们在routers文件夹下建的两个文件,遍历拿到地址放在autoLoadRoutes中
最后在APP中用Suspense 包裹Switch
import {
Suspense } from 'react';
<Suspense fallback={
<div />}>
<Switch>
{
routes.map((route: any) => (
<Route path={
route.path} key={
route.path} component={
route.component} />
))}
</Switch>
</Suspense>