简体   繁体   English

使用 webpack 响应延迟加载模块

[英]React lazy load modules with webpack

I have a file called routes.js我有一个名为routes.js的文件

 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, }, ], }, ]

In my app.js I import routes and do something like this在我的 app.js 中,我导入路由并执行类似的操作

 <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>;

This works without errors!这工作没有错误! But I want to split my code to reduce my bundle size.但我想拆分我的代码以减少我的包大小。 How do I do it in routes.js file?如何在routes.js文件中执行此操作?

Very simple with react.lazy: react.lazy 非常简单:

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,
      },
    ],
  },
]

NOTE: Make sure you have a Suspense component with a fallback prop somewhere in your tree above where you are rendering these components.注意:确保你有一个Suspense组件,在你渲染这些组件的树上的某个地方有一个fallback道具。

Like this:像这样:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM