一度に多くのルーティング ファイルをロードすると、最初のロード速度が非常に遅くなります。次のように、遅延ロードの形式で
新しいフォルダー 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;
vite の import.meta.globEager() をindex.ts で使用してファイルを自動的にインポートします
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;
コンソールは、作成した 2 つのファイルを routers フォルダーの下に自動的にインポートし、アドレスを取得して autoLoadRoutes に配置し、
最後にアプリでスイッチを Suspense でラップすることを確認できます。
import {
Suspense } from 'react';
<Suspense fallback={
<div />}>
<Switch>
{
routes.map((route: any) => (
<Route path={
route.path} key={
route.path} component={
route.component} />
))}
</Switch>
</Suspense>