React Router 4.0 + webpack 實現組件按需加載

  網上關於React Router 4.0的按需加載文章有不少,大體的思路都同樣,可是其實具體實現起來卻要根據本身的實際狀況來定,這裏主要介紹一下個人實現方式。react

  主要方式是經過Route組件的render方法加載一個空的組件做爲中間,經過空的組件用來加載具體的頁面js文件,而後這個組件的內部加載完成的時候就使用webpack 的 import方法動態請求js,當js請求成功後,這個空組件顯示具體的加載js內容,提及來比較晦澀,直接上代碼。webpack

  一、先看看中間組件,(因爲我這裏使用了Typescript, 代碼裏的ts代碼不感興趣的能夠直接忽略便可)
web

  

import * as React from 'react';
export namespace LoadComponentAsync {
    export interface Props {
        componentName: string
    }

    export interface State {
        Component: React.ReactType
    }
}

export class LoadComponentAsync extends React.Component<LoadComponentAsync.Props, LoadComponentAsync.State> {
    constructor(props) {
        super(props)
        this.state = {
            Component: null
        }
    }

    componentDidMount() {
    // 這裏使用的import進行動態加載組件 import(`..
/componentPublicPath/${this.props.componentName}` /* webpackChunkName: "[request]" */ ).then(Component => { this.setState({ Component: Component.default }) }) } render () { let Component = this.state.Component if (Component) { return <Component /> } else { return null } } }

   是的,就是這麼簡單的一個空組件。json

  二、Router部分怎麼使用這個組件呢?babel

<Switch>
      <Route path='/some/path'} exact render={() => {
          return <LoadComponentAsync key={'someKey'} componentName={yourComponentName}/>
      }}/> 
    <Route path='/some/path2'} exact render={() => {
          return <LoadComponentAsync key={'someKey2'} componentName={yourComponentName2}/>
      }}/>  
</Switch>

  是的仍是這麼的超級簡單。this

   三、具體的思路上面的已是核心代碼了,spa

  你可能還須要配置一下東西,默認的狀況你每次加載對應的路由請求的js多是0.js 1.js 2.js這個樣子的,顯然十分醜陋,我想看他們每一個js組件的具體名字是什麼怎麼辦呢?code

  首先找的你的webpack.config.js,而後,加入一個chunkFilename, component

   

  Yes, 就是這樣。而後注意到上面的import裏面有個註釋了嗎blog

  

  這是個啥,Magic Comments, 魔法註釋 這個webpackChunkName能夠告訴webpack 每一個 chunkname 是什麼,這裏我[request]表示的意思是每次請求的組件名稱做爲chunkname , 

  本文正文結束啦。

  順便提一句,若是你的 Magic Comments 不生效注意你的.babelrc 或者tsconfig.json裏是否有去掉註釋的邏輯(相似removeComments: true ),有的話須要關掉,而後就能夠完美按需加載你的組件嘍。

 

                                                                      注:本文出自博客園 https://home.cnblogs.com/u/mdengcc/ ,轉載請註明出處。 稍微尊重一下原創OK?

相關文章
相關標籤/搜索