[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 ...
随机推荐
- HDU 4764 Stone (2013长春网络赛,水博弈)
Stone Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- STM32F4, USB HS with ULPI and Suspend/Wakeup
Hi guys,I am in need of your help, unfortunately STs documentation is lacking some information here. ...
- 在ASP.NET MVC中使用Knockout实践03,巧用data参数
使用Knockout,当通过构造函数创建View Model的时候,构造函数的参数个数很可能是不确定的,于是就有了这样的一个解决方案:向构造函数传递一个object类型的参数data. <inp ...
- Delphi实例分析:远程传输数据和文件
在Windows操作系统的平台上,WinSock是首选的网络编程接口,用于在网络上传输数据和交换信息,它构成了Windows操作系统进行网络编程的基础.对于编写网络应用程序来说,WinSock是一门非 ...
- NSNotificationCenter消息注册与撤销
苹果的消息机制是个非常好用的东西,当需要在类的各个实例之间传递消息或者写一些事件驱动的程序时,绝对是个不错的工具.但是使用时一不小心就会造成引用已经被dealloc的对象的错误,引起程序崩溃.于是,在 ...
- WCF:该不该用枚举值
WCF支持枚举,不过在个别场景下会出现服务消费失败,如:传递或返回的枚举值(本质是int或其它)没有在枚举中定义.这种异常还很难定位,出现这种情况一般是因为BUG,因此简单的放弃使用枚举可能不是一个明 ...
- cloudera项目源代码
以下项目都需要安装git,Linux的git还是比较容易安装的,windows的git安装参考项目区域:软件版本控制-在Windows中使用Git视频介绍 git相关软件安装参考win7安装 git软 ...
- 给hmailserver添加SSL支持
我们使用stunnel来给hmailserver添加ssl支持,stunnel是一个开源跨平台提供全局TLS/SSL支持的软件,它可以给很多本身不支持ssl的软件来提供安全的加密连接,同样可以用于hm ...
- End2endIT
"C:\Program Files\Java\jdk1.8.0_112\bin\java" -ea -Didea.test.cyclic.buffer.size=1048576 & ...
- fabric工具
./cryptogen generate --output="a" --config=crypto-config.yaml # Copyright IBM Corp. All Ri ...