Javascript 使用webpack响应延迟加载模块

Javascript 使用webpack响应延迟加载模块,javascript,reactjs,webpack,Javascript,Reactjs,Webpack,我有一个名为routes.js的文件 从“../src/components/Country/Country”进口的国家; 来自“../src/components/country/CountriesList”的进口国; 导出常量路由=[ { 名称:'国家', 儿童:[ { 名称:“创建”, 路径:'/country', 构成部分:国家, }, { 名称:“更新”, 路径:'/update country', 构成部分:国家, 伊希登:没错, }, { 名称:“视图”, 路径:'/countr

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

从“../src/components/Country/Country”进口的国家;
来自“../src/components/country/CountriesList”的进口国;
导出常量路由=[
{
名称:'国家',
儿童:[
{
名称:“创建”,
路径:'/country',
构成部分:国家,
},
{
名称:“更新”,
路径:'/update country',
构成部分:国家,
伊希登:没错,
},
{
名称:“视图”,
路径:'/countries',
构成部分:国家,
},
],
},

]
使用react.lazy非常简单:

从'react'导入{lazy};
//只要换一行就行了
const Country=lazy(()=>import('../src/components/Country/Country');
const Countries=lazy(()=>import('../src/components/country/CountriesList');
导出常量路由=[
{
名称:'国家',
儿童:[
{
名称:“创建”,
路径:'/country',
构成部分:国家,
},
{
名称:“更新”,
路径:'/update country',
构成部分:国家,
伊希登:没错,
},
{
名称:“视图”,
路径:'/countries',
构成部分:国家,
},
],
},
]
注意:确保在渲染这些组件的树上方的某个位置有一个
暂挂
组件,该组件带有一个
回退
道具

像这样:

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>
import React,{suspend}来自'React';
{路线
.flatMap((项目)=>items.children)
.map({component,path})=>(
))}

使用react.lazy非常简单:

从'react'导入{lazy};
//只要换一行就行了
const Country=lazy(()=>import('../src/components/Country/Country');
const Countries=lazy(()=>import('../src/components/country/CountriesList');
导出常量路由=[
{
名称:'国家',
儿童:[
{
名称:“创建”,
路径:'/country',
构成部分:国家,
},
{
名称:“更新”,
路径:'/update country',
构成部分:国家,
伊希登:没错,
},
{
名称:“视图”,
路径:'/countries',
构成部分:国家,
},
],
},
]
注意:确保在渲染这些组件的树上方的某个位置有一个
暂挂
组件,该组件带有一个
回退
道具

像这样:

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>
import React,{suspend}来自'React';
{路线
.flatMap((项目)=>items.children)
.map({component,path})=>(
))}

这与导入('../src/components/Country/Country')相同
?@PathumKalhan-否,您需要向
React.lazy
传递回调,该回调仅在呈现组件时加载组件。这与
const Country=()=>import('../src/components/Country/Country')相同吗
?@PathumKalhan-否,您需要将回调传递给
React.lazy
,该回调仅在呈现组件时加载组件。