[React] Asynchronously Load webpack Bundles through Code-splitting and React Suspense
One approach to building high performance applications with webpack is to take advantage of code-splitting to only load the needed JavaScript on initial load and asynchronously load additional JavaScript bundles when needed. In this lesson, we'll create add some code-splitting to our placeholder application and configure our project to support the dynamic import() syntax.
Install:
npm i -D @babel/plugin-syntax-dynamic-import
Add plugin into webpack config:
plugins: [
...
'@babel/plugin-syntax-dynamic-import'
]
What we want to do is lazy loading a Warning component, and also utilize the code spliting from webpack:
Here is the component we want to lazy load in:
import React from 'react'
export default () => <span className={'warning'}>Take it easy!</span>
App.js:
import React from 'react'
import {hot} from 'react-hot-loader' const Warning = React.lazy(() => import('./Warning')) class App extends React.Component {
state = {
count: 0
} increment = () => {
this.setState(state => ({count: state.count + 1}))
} decrement = () => {
this.setState(state => ({count: state.count - 1}))
} render() {
const {count} = this.state
return (
<div>
<h1>Hello World.</h1>
<h2 className={count > 10 ? 'warning' : null}>
Count: {count}
</h2>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
{count > 10 ?
<React.Suspense fallback={null}>
<Warning />
</React.Suspense>
: null}
</div>
)
}
} export default hot(module)(App)
We use React.lazy + dynamic import syntax:
const Warning = React.lazy(() => import('./Warning'))
Then we use lazy loaded Warning component with React.Suspense:
<React.Suspense fallback={null}>
<Warning />
</React.Suspense>
'fallback' take a jsx element which will be shown when doing the lazy loading.
So what if the Warning component failed to load?
Here is where Error Boundries comes in to play:
class MyErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export defualt MyErrorBoundry;
Then wrap your Suspense component with boundry:
<MyErrorBoundary>
<React.Suspense fallback={null}>
<Warning />
</React.Suspense>
</MyErrorBoundary>
Now we can get benifits from lazy loading and also safety from the boundry
More about Code splitting.
[React] Asynchronously Load webpack Bundles through Code-splitting and React Suspense的更多相关文章
- webpack优化之code splitting
作为当前风头正盛的打包工具,webpack风靡前端界.确实作为引领了一个时代的打包工具,很多方面都带来了颠覆性的改进,让我们更加的感受到自动化的快感.不过最为大家诟病的一点就是用起来太难了. 要想愉快 ...
- webpack async load modules & dynamic code splitting
webpack async load modules & dynamic code splitting webpack 按需/异步加载/Code Splitting webpack loade ...
- webpack Code Splitting浅析
Code Splitting是webpack的一个重要特性,他允许你将代码打包生成多个bundle.对多页应用来说,它是必须的,因为必须要配置多个入口生成多个bundle:对于单页应用来说,如果只打包 ...
- [转] react-router4 + webpack Code Splitting
项目升级为react-router4后,就尝试着根据官方文档进行代码分割.https://reacttraining.com/react-router/web/guides/code-splittin ...
- react-router4 + webpack Code Splitting
项目升级为react-router4后,就尝试着根据官方文档进行代码分割.https://reacttraining.com/react-router/web/guides/code-splittin ...
- [Webpack 2] Maintain sane file sizes with webpack code splitting
As a Single Page Application grows in size, the size of the payload can become a real problem for pe ...
- webpack 利用Code Splitting 分批打包、按需下载
webpack中的解决方案——Code Splitting,简单来说就是按需加载(下载),如果是requireJS对应的AMD的方案中这本是在正常不过了.但是在webpack中All in one的思 ...
- webpack 和 code splitting
Code Splitting指的是代码分割,那么什么是代码分割,webpack和code splitting又有什么样的联系呢? 使用npm run dev:"webpack-dev-ser ...
- 借助Code Splitting 提升单页面应用性能
近日的工作集中于一个单页面应用(Single-page application),在项目中尝试了闻名已久的Code splitting,收获极大,特此分享. Why we need code spli ...
随机推荐
- 使用36-pin的STM32输出VGA, VGA output using a 36-pin STM32
使用36-pin的STM32输出VGA 手头上有个项目需要通过单片机来控制将图像显示在LCD上,在网上搜了一阵子,发现都是使用的FPGA做的, 开始自己对FPGA不是很熟,一直在用的也是ARM系列的, ...
- cmsis dap interface firmware
cmsis dap interface firmware The source code of the mbed HDK (tools + libraries) is available in thi ...
- jQuery $('div>ul') $('div ul'
$('div>ul')是<div>的直接后代里找<ul>: 而$('div ul')是在<div>的所有后代里找<ul>.
- .NET基于Eleasticsearch搭建日志系统实战演练
一.需求背景介绍 1.1.需求描述 大家都知道C/S架构模式的客户端应用程序(比如:WinForm桌面应用.WPF.移动App应用程序.控制台应用程序.Windows服务等等)的日志记录都存储在本地客 ...
- 【ELK】5.spring boot日志集成ELK,搭建日志系统
阅读前必看: ELK在docker下搭建步骤 spring boot集成es,CRUD操作完整版 ============================================== 本章集成 ...
- WordPress基础:wp_title
使用标题格式:首页(网站标题 - 网站副标题),其他页面(页面标题 | 网站标题) wp_title(分隔符,是否直接显示,分隔符显示在哪里) wp_title用在首页是没效果的,需要自己格式化一下 ...
- 给js创建的一个input数组绑定click事件
<html> <body> <input type="button" name="input[]" value="按钮1 ...
- Fiddler抓包12-AutoResponder返回本地数据(mock)
前言 mock可以说是面试必问的话题的,我第一次接触mock的时候也是一脸懵逼.虽然fiddler工具用了很久,里面的打断点,设置自动返回数据功能都用过. mock说的通俗一点就是模拟返回数据,只是面 ...
- Unity Shader _Time 的单位
名称 类型 说明 _Time float4 t 是自该场景加载开始所经过的时间,4个分量分别是 (t/20, t, t*2, t*3) _SinTime float4 t 是时间的正弦值,4个分量分别 ...
- jQuery Ajax方式上传文件实现暂停或取消上传
未上传时要实现取消,很简单... 但如果用户点击了上传,并加载了进度信息... 2017-05-04再次改进.在上传过程中用户可以按 Esc 来取消上传(取消当前上传,或者是全部上传)... 也可以在 ...