首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与webpack一起反应延迟加载模块

与webpack一起反应延迟加载模块
EN

Stack Overflow用户
提问于 2020-11-17 23:50:07
回答 1查看 309关注 0票数 1

我有一个名为routes.js的文件

代码语言:javascript
复制
import Country from '../src/components/country/Country';
import Countries from '../src/components/country/CountriesList';

export const routes = [
{
    name: 'COUNTRY',
    children: [
      {
        name: 'Create',
        path: '/country',
        component: Country,
      },
      {
        name: 'Update',
        path: '/update-country',
        component: Country,
        isHidden: true,
      },
      {
        name: 'View',
        path: '/countries',
        component: Countries,
      },
    ],
  },
]

在我的app.js中,我导入路由并执行如下操作

代码语言:javascript
复制
<Switch>
  <Route path="/" exact component={Login}></Route>
  <Route path="/permission-denied" exact component={PermissionDenied}></Route>

  {routes
    .flatMap((items) => items.children)
    .map(({ component, path }) => (
      <ProtectedRoute component={component} exact path={path} />
    ))}

  <Route component={NotFound}></Route>
</Switch>;

这是没有错误的工作!但是我想拆分我的代码,以减少我的包大小。如何在routes.js文件中执行此操作?

EN

回答 1

Stack Overflow用户

发布于 2020-11-18 00:06:52

使用react.lazy非常简单:

代码语言:javascript
复制
import { lazy } from 'react';

// just change these lines
const Country = lazy(() => import('../src/components/country/Country'));
const Countries = lazy(() => import('../src/components/country/CountriesList'));

export const routes = [
{
    name: 'COUNTRY',
    children: [
      {
        name: 'Create',
        path: '/country',
        component: Country,
      },
      {
        name: 'Update',
        path: '/update-country',
        component: Country,
        isHidden: true,
      },
      {
        name: 'View',
        path: '/countries',
        component: Countries,
      },
    ],
  },
]

注意:请确保在渲染这些组件的树上方的某个位置有一个带有fallback属性的Suspense组件。

如下所示:

代码语言:javascript
复制
import React, { Suspense } from 'react';


<Suspense fallback={<></>}>
    <Switch>
        <Route path="/" exact component={Login}></Route>
        <Route path="/permission-denied" exact component={PermissionDenied}></Route>

        {routes
            .flatMap((items) => items.children)
            .map(({ component, path }) => (
            <ProtectedRoute component={component} exact path={path} />
            ))}

        <Route component={NotFound}></Route>
    </Switch>
</Suspense>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64878588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档