1. bundle-loader插件
根据官网的使用方法,首先安装bundle-loader依赖,npm i --save bundle-loader
,在页面中使用一个异步加载的组件包裹我们需要引入的组件,然后传给Route,这里需要注意,引入页面组件的方式与之前也有不同,需要在平常的引入路径前加上bundle-loader?lazy&name=[name]!
这个前缀
import lazyLoad from './utils/lazyLoad/lazyLoad';
import BasicLayout from 'bundle-loader?lazy&name=[name]!./layouts/BasicLayout';
<BrowserRouter>
<Switch>
<Route path="/login" component={login}/>
<Route path='/404' component={page404}/>
<Route path="/" component={lazyLoad(BasicLayout)}/>
</Switch>
</BrowserRouter>
异步包裹组件 lazyLoad
import React from 'react';
import Bundle from './Bundle';
// 默认加载组件,可以直接返回 null
const Loading = () => <div>Loading...</div>;
/*
包装方法,第一次调用后会返回一个组件(函数式组件)
由于要将其作为路由下的组件,所以需要将 props 传入
*/
const lazyLoad = loadComponent => props => (
<Bundle load={loadComponent}>
{Comp => (Comp ? <Comp {...props} /> : <Loading />)}
</Bundle>
);
export default lazyLoad;
核心Bundle组件
import React from 'react';
export default class Bundle extends React.Component {
state = {
mod: null
}
componentWillMount() {
this.load(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps);
}
}
// load 方法,用于更新 mod 状态
load(props) {
// 初始化
this.setState({
mod: null
});
/*
调用传入的 load 方法,并传入一个回调函数
这个回调函数接收 在 load 方法内部异步获取到的组件,并将其更新为 mod
*/
props.load(mod => {
this.setState({
mod: mod.default ? mod.default : mod
});
});
}
render() {
/*
将存在状态中的 mod 组件作为参数传递给当前包装组件的'子'
*/
return this.state.mod ? this.props.children(this.state.mod) : null;
}
}
安装上述代码放于项目中,并且用正确的方式引入组件,即可开启异步加载功能。
但是有一点需要注意,在create-react-app中使用bundle-loader功能会报错
$KJ%DK_J6T6J)JT9~TWXJPU.png这是因为在脚手架中配置了相关的eslint规则,它不允许我们使用bundle-loader的方式引入组件。这条规则在prod和dev的webpack文件中都有配置,如果注释这一段代码则可以正常编译。
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
2. 使用import()异步引入功能
Webpack loaders are not supported by Create React App.
Moreover, you don’t need bundle-loader to implement lazy loading.
It is already supported out of the box with dynamic import().
我Google找到了这个答案,建议我们在create-react-app脚手架中使用import()异步引入的功能。
那么import()的使用方法如下
import AsyncComponent from './utils/AsyncLoad/AsyncComponent';
const BasicLayout = AsyncComponent(() => import("./layouts/BasicLayout"));
<BrowserRouter>
<Switch>
<Route path="/login" component={login}/>
<Route path='/404' component={page404}/>
<Route path="/" component={BasicLayout}/>
</Switch>
</BrowserRouter>
AsyncComponent文件代码
import React, { Component } from "react";
export default function AsyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
}
至此import()的异步加载引入成功
image.png3. react-loadable
Now this seems really easy to implement but you might be wondering what happens if the request to import the new component takes too long, or fails. Or maybe you want to preload certain components. For example, a user is on your login page about to login and you want to preload the homepage.
It was mentioned above that you can add a loading spinner while the import is in progress. But we can take it a step further and address some of these edge cases. There is an excellent higher order component that does a lot of this well; it’s called react-loadable.
作者给出了import()实现异步加载的缺点:1. 如果组件加载时间过长或者失败。2. 或者你想预加载某些组件,比如用户在你的登录页面上即将登录所以你想要预加载主页。
上面提到过,你可以在导入过程中添加加载微调器。但我们可以更进一步,解决其中一些边缘情况。有一个很好的高阶组件可以很好地完成这些工作,那就是react-loadable。
使用方法
import Loadable from 'react-loadable';
import MyLoadingComponent from './utils/MyLoadingComponent';
const BasicLayout = Loadable({
loader: () => import("./layouts/BasicLayout"),
loading: MyLoadingComponent
});
<BrowserRouter>
<Switch>
<Route path="/login" component={login}/>
<Route path='/404' component={page404}/>
<Route path="/" component={BasicLayout}/>
</Switch>
</BrowserRouter>
MyloadingComponent文件代码
/**
* Created by ZhangLynn on 2018/7/31
**/
import React from 'react';
const MyLoadingComponent = ({isLoading, error}) => {
// Handle the loading state
if (isLoading) {
return <div>Loading...</div>;
}
// Handle the error state
else if (error) {
return <div>Sorry, there was a problem loading the page.</div>;
}
else {
return null;
}
};
export default MyLoadingComponent;
至此功能已经添加,并且能够编译成功
image.png
https://serverless-stack.com/chapters/code-splitting-in-create-react-app.html
https://www.jianshu.com/p/697669781276
网友评论