天天看點

webpack+react-router實作代碼拆分按需加載(上)webpack+react-router實作代碼拆分按需加載(中)webpack+react-router實作代碼拆分按需加載(下)

    目前由H5內建開發的app小應用越來越來多,即在在一個原生的app平台下內建很多由web頁面構成的小應用,是以我們可能在一個工程下開發多個小應用,部署整個工程之後,由原生端通過openWebview打開相關的路由,為了打開一個web應用時不附加别的應用的代碼,不妨試試下面的js檔案代碼:

一、安裝bundle-loader依賴

npm install --save-dev bundle-loader      

webpack相關配置如下:

module: {
    rules: [
      {
      test: /\.(js|jsx)$/,
      include: path.resolve(__dirname,"./src/modules/**/"),
      use: [
       {
        loader: "bundle-loader",
        options: {
           lazy: true,
           name: '[name]'
        }
       }
      ]
     }
    ]
}      

二、定義一個高階元件(HOC)

import React, {Component} from 'react'

class Bundle extends Component {
   constructor(props) {
      super(props);
      this.state = {
         mod: null
      }
   }
   
   componentWillMount() {
      this.load(this.props)
   }
   
   componentWillReceiveProps(nextProps) {
      if (nextProps.load !== this.props.load) {
         this.load(nextProps)
      }
   }
   
   load(props) {
      this.setState({
         mod: null
      });
      props.load((mod) => {
         this.setState({
            mod: mod.default ? mod.default : mod
         })
      })
   }
   
   render() {
      if (!this.state.mod)
         return false;
      return this.props.children(this.state.mod)
   }
}

export default function lazy(lazyClass) {
   return function Wrapper(props) {
      return <Bundle load={lazyClass}>
         {(Clazz) => <Clazz {...props} />}
      </Bundle>
   }
}      

三、路由相關配置

import BindInfo from 'bundle-loader?lazy&name=userBind-chunk!../modules/userBind/info/Info';

import Bundle from './Bundle';      
<Route path='userBind'>
    <IndexRoute component={Bundle(UserBind)}/>
    <Route path="info/:id"  component={Bundle(BindInfo)}/>
</Route>      

四、正常進行webpack打包操作時可以看到代碼已經拆分成了數個chunk.js,打開浏覽器可以看到按需加載的效果。

webpack+react-router實作代碼拆分按需加載(上)webpack+react-router實作代碼拆分按需加載(中)webpack+react-router實作代碼拆分按需加載(下)
webpack+react-router實作代碼拆分按需加載(上)webpack+react-router實作代碼拆分按需加載(中)webpack+react-router實作代碼拆分按需加載(下)

webpack+react-router實作代碼拆分按需加載(中)

webpack+react-router實作代碼拆分按需加載(下)