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:

  1. npm i -D @babel/plugin-syntax-dynamic-import

Add plugin into webpack config:

  1. plugins: [
  2. ...
  3. '@babel/plugin-syntax-dynamic-import'
  4. ]

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:

  1. import React from 'react'
  2.  
  3. export default () => <span className={'warning'}>Take it easy!</span>

App.js:

  1. import React from 'react'
  2. import {hot} from 'react-hot-loader'
  3.  
  4. const Warning = React.lazy(() => import('./Warning'))
  5.  
  6. class App extends React.Component {
  7. state = {
  8. count: 0
  9. }
  10.  
  11. increment = () => {
  12. this.setState(state => ({count: state.count + 1}))
  13. }
  14.  
  15. decrement = () => {
  16. this.setState(state => ({count: state.count - 1}))
  17. }
  18.  
  19. render() {
  20. const {count} = this.state
  21. return (
  22. <div>
  23. <h1>Hello World.</h1>
  24. <h2 className={count > 10 ? 'warning' : null}>
  25. Count: {count}
  26. </h2>
  27. <button onClick={this.increment}>+</button>
  28. <button onClick={this.decrement}>-</button>
  29. {count > 10 ?
  30. <React.Suspense fallback={null}>
  31. <Warning />
  32. </React.Suspense>
  33. : null}
  34. </div>
  35. )
  36. }
  37. }
  38.  
  39. export default hot(module)(App)

We use React.lazy + dynamic import syntax:

  1. const Warning = React.lazy(() => import('./Warning'))

Then we use lazy loaded Warning component with React.Suspense:

  1. <React.Suspense fallback={null}>
  2. <Warning />
  3. </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:

  1. class MyErrorBoundary extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { hasError: false };
  5. }
  6.  
  7. static getDerivedStateFromError(error) {
  8. // Update state so the next render will show the fallback UI.
  9. return { hasError: true };
  10. }
  11.  
  12. componentDidCatch(error, info) {
  13. // You can also log the error to an error reporting service
  14. logErrorToMyService(error, info);
  15. }
  16.  
  17. render() {
  18. if (this.state.hasError) {
  19. // You can render any custom fallback UI
  20. return <h1>Something went wrong.</h1>;
  21. }
  22.  
  23. return this.props.children;
  24. }
  25. }
  26.  
  27. export defualt MyErrorBoundry;

Then wrap your Suspense component with boundry:

  1. <MyErrorBoundary>
  2. <React.Suspense fallback={null}>
  3. <Warning />
  4. </React.Suspense>
  5. </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的更多相关文章

  1. webpack优化之code splitting

    作为当前风头正盛的打包工具,webpack风靡前端界.确实作为引领了一个时代的打包工具,很多方面都带来了颠覆性的改进,让我们更加的感受到自动化的快感.不过最为大家诟病的一点就是用起来太难了. 要想愉快 ...

  2. webpack async load modules & dynamic code splitting

    webpack async load modules & dynamic code splitting webpack 按需/异步加载/Code Splitting webpack loade ...

  3. webpack Code Splitting浅析

    Code Splitting是webpack的一个重要特性,他允许你将代码打包生成多个bundle.对多页应用来说,它是必须的,因为必须要配置多个入口生成多个bundle:对于单页应用来说,如果只打包 ...

  4. [转] react-router4 + webpack Code Splitting

    项目升级为react-router4后,就尝试着根据官方文档进行代码分割.https://reacttraining.com/react-router/web/guides/code-splittin ...

  5. react-router4 + webpack Code Splitting

    项目升级为react-router4后,就尝试着根据官方文档进行代码分割.https://reacttraining.com/react-router/web/guides/code-splittin ...

  6. [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 ...

  7. webpack 利用Code Splitting 分批打包、按需下载

    webpack中的解决方案——Code Splitting,简单来说就是按需加载(下载),如果是requireJS对应的AMD的方案中这本是在正常不过了.但是在webpack中All in one的思 ...

  8. webpack 和 code splitting

    Code Splitting指的是代码分割,那么什么是代码分割,webpack和code splitting又有什么样的联系呢? 使用npm run dev:"webpack-dev-ser ...

  9. 借助Code Splitting 提升单页面应用性能

    近日的工作集中于一个单页面应用(Single-page application),在项目中尝试了闻名已久的Code splitting,收获极大,特此分享. Why we need code spli ...

随机推荐

  1. STM32的CRC32 软件实现代码

    对于STM32的32位CRC,如果假定它的一个主要目的是为了校验往内部FLASH存储数据的可靠性,那么(余数)初值是全1当然是比较合理的.由于STM32的32位CRC是纯32位,即每次必须输入32位的 ...

  2. 在Delphi中DBGrid有一个MouseMove事件,当鼠标移动时怎么知道光标在哪个单元格上面

    procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);var coords:TGr ...

  3. 在ASP.NET MVC4中实现同页面增删改查,无弹出框02,增删改查界面设计

    在上一篇"在ASP.NET MVC4中实现同页面增删改查,无弹出框01,Repository的搭建"中,已经搭建好了Repository层,本篇就剩下增删改查的界面了......今 ...

  4. 如何:为iOS 的方法写注释 让xcode 能够索引得到?

    如何:为iOS 的方法写注释 让xcode 能够索引得到? 按照如下方法为ios项目写注释: 将会让xcode能够索引得到如下结果:

  5. 利用ViewStub来延迟加载视图

    很多情况下,我们的视图可能会随着用户的操作的不同而变化,比如一个新的页面包含多个控件,但仅仅在用户点击这个按钮后,所有的控件才能完全显示.也就是说一上来可能就显示一个控件,点击按钮后把其他隐藏的控件再 ...

  6. Eclipse with ADT的安装和配置

    我们从安卓官方网站(https://developer.android.com/sdk/index.html#download)下载下来的eclipse是捆绑好了ADT的,所以不用自己安装插件,十分方 ...

  7. Curl操作Elasticsearch的常用方法

    Elasticsearch对于文档操作,提供了以下几种API,本文就说明如何使用curl方式来调用这些API. API种类 单文档操作API 1.* Index API 索引文档 * 为文档创建索引 ...

  8. SVG.js 元素操作整理(二)-Transform

    一.transform()获取或设置矩阵变换 var draw = SVG('svg1').size(300, 300); //Transforming SVG元素矩阵变换 var rect = dr ...

  9. 理解Java ThreadLocal

    ThreadLocal是什么 早在JDK 1.2的版本中就提供Java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路.使用这个工具类可以很简洁地 ...

  10. [转]11个在线编码大赛,与全球程序员PK

    From : http://news.cnblogs.com/n/187196/ 英文原文:10 Online Coding Contests For Programmers! 如果你拥有出色的编码技 ...