React路由懒加载lazy、Suspense以及Vite的Glob 导入文件

一次性加载太多的路由文件会使首次加载的速度很慢,建议将路由以懒加载的形式
新建文件夹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>

猜你喜欢

转载自blog.csdn.net/weixin_47541876/article/details/128816809