@loadable/components是如何實(shí)現(xiàn)懶加載的

先看下官方文檔是如何使用@loadable/component

import loadable from '@loadable/component'
const OtherComponent = loadable(() => import('./OtherComponent'))
function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  )
}

loadable(() => import('./OtherComponent')) 的返回值是一個(gè)React組件。那究竟是如何做到懶加載的?

本文不會(huì)講解import('./OtherComponent')如何分包,如果想了解請(qǐng)自行查閱資料。

createLoadable

源碼中loadablecreateLoadable生成。createLoadble接受defaultResolveComponentrender兩個(gè)參數(shù),執(zhí)行后返回loadable

import React from 'react'
import createLoadable from './createLoadable'
import { defaultResolveComponent } from './resolvers'

export const { loadable, lazy } = createLoadable({
  defaultResolveComponent,
  render({ result: Component, props }) {
    return <Component {...props} />
  },
})

至于defaultResolveComponent這里先不用管,下文使用到會(huì)介紹。

接下來(lái)就是最核心的createLoadable ,它的代碼框架如下:

image.png

createLoadable內(nèi)部定義并返回了loadablelazy兩個(gè)函數(shù)。其中我們的關(guān)注重點(diǎn)是官方文檔提到的loadable

loadable

loadable有2個(gè)參數(shù):

  1. 構(gòu)造函數(shù),
  2. options選項(xiàng)。

首先,loadable會(huì)先執(zhí)行resolveConstructor,對(duì)構(gòu)造函數(shù)包裝:

const ctor = resolveConstructor(loadableConstructor); 

包裝后,ctor的值如下:

const ctor = {
    requireAsync: () => import('./OtherComponent'),
    resolve() {
        return undefined
    },
    chunkName() {
        return undefined
    }
}

編譯后的ctor值:


loadable:component.png

InnerLoadable

loadable內(nèi)部還定義了一個(gè)類(lèi)組件InnerLoadable

  class InnerLoadable extends React.Component {
      constructor(props) {
        super(props)

        this.state = {
          result: null,
          error: null,
          loading: true,
          cacheKey: getCacheKey(props),
        }
      }  
      // ........  
   }

    const EnhancedInnerLoadable = withChunkExtractor(InnerLoadable)
    const Loadable = React.forwardRef((props, ref) => (
      <EnhancedInnerLoadable forwardedRef={ref} {...props} />
    ))
    
    Loadable.displayName = 'Loadable';
    return Loadable;

其中withChunkExtractor是一個(gè)高階組件,InnerLoadable經(jīng)過(guò)HOC withChunkExtractor包裝后再由React.forwardRef包裝一次。
因此,Loadable實(shí)質(zhì)上也是一個(gè)高階組件,至于具體是如何加載bundle的請(qǐng)繼續(xù)往下閱讀。

組件加載階段請(qǐng)求bundle

在生命周期componentDidMount執(zhí)行loadAsync

    componentDidMount() {
       this.mounted = true
    
       // .....
       
       // component might be resolved synchronously in the constructor
       if (this.state.loading) {
            this.loadAsync()
        }
      }
 

loadAsync中去加載bundle(實(shí)際上源碼內(nèi)部調(diào)用了多個(gè)方法,為了閱讀方便,我把方法拆開(kāi)簡(jiǎn)化后都寫(xiě)到loadAsync中),加載成功后bundle存到result,同時(shí)loading變?yōu)閒alse。

  loadAsync() {
      const { __chunkExtractor, forwardedRef, ...props } = this.props;
        
        /**
        *  這一步會(huì)請(qǐng)求需要懶加載的包, 對(duì)應(yīng)代碼import('./OtherComponent')
        */
       let promise = ctor.requireAsync(props);  
        
        promise
          .then(loadedModule => {
            const result = resolve(loadedModule, this.props);
            if(this.mounted) {
               this.setState({
                 result,
                 loading: false,
               })
            }            
          })
          .catch(error => this.safeSetState({ error, loading: false }))

        return promise
   }

resolve中判斷使用者是否傳入resolveComponent,如果有就用resolveComponent去處理module和props,如果沒(méi)有則使用defaultResolveComponent返回module。

   function resolve(module, props) {
      const Component = options.resolveComponent
        ? options.resolveComponent(module, props)
        : defaultResolveComponent(module)

      return Component
   }

defaultResolveComponent也是一個(gè)函數(shù),傳入一個(gè)module作為參數(shù),如果是esModule則返回module.default ,否則返回 module.default || module:

export function defaultResolveComponent(loadedModule) {
  return loadedModule.__esModule
    ? loadedModule.default
    : loadedModule.default || loadedModule
}

componentDidMount加載bundle后,loading變?yōu)閒alse,在render中執(zhí)行createLoadable的參數(shù)render后返回:

    render() {
        const {
          forwardedRef,
          fallback: propFallback,
          __chunkExtractor,
          ...props
        } = this.props
        const { loading, result } = this.state
    
        const fallback = propFallback || options.fallback || null

        if (loading) {
          return fallback
        }

        return render({
          fallback,
          result,
          options,
          props: { ...props, ref: forwardedRef },
        })
      }

代碼中執(zhí)行的render如下:


render.png

總結(jié)

loadable是一個(gè)高階組件,在componentDidMount加載 bundle (() => import('./xxx')被打包后的bundle),如果沒(méi)有加載或者加載未完成則在render中渲染fallback,加載完成則渲染組件。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容