随笔

React-Router-4 Lazyload Webpack2 Code Split

哇哇哇 昨晚搞到三点多~~~
早上起来才弄出来 (-。-;

intro

目前适用的有两种

  • bundle-loader
  • import() 这里呢,我用 import()

write

首页,参考引用一写出bundle组件
要注意的是,props.load返回的是promise

const lazyRoute = (func,props,auth) =>  {
    if(auth){
        auth = props.location.pathname
    }
    return <Bundle auth={auth} load={func}>
        {(Com) => (<Com {...props} />)}
    </Bundle>
}

const IndexPage = () => lazyRoute(() => import('./page/index'),this.props)

此处 IndexPage我是放到render中的,因为外边拿不到props

其中也遇到了另一个问题 用户更新状态不能实时生效,只能注销的时候手动redirect

Bundle -> Render -> ChildRen -> Render

有一些模糊的概念,但还是不太清楚 2333

2017-5-15 注

一个比较hack的方法...

{
  !auth ? <Redirect to={'/login'} />:(
    <div>
        <Route exact path='/' component={Park} />                  
        <Route path='/logout' component={Login} />
        <Route exact path="/admin/diary" component={DiaryList} />
        <Route path="/admin/diary/create" component={CreateDiary} />
    </div>
  )
}

这样的话在访问受保护的页面时同样会自动跳到登陆
回源同样也是适用,获取 location 就是啦~~

webpack 配置

这个应该和以前的版本是没有区别的 比如我的

filename: "assets/[name].bundle.js",
chunkFilename: '[name]-[id].[chunkhash:8].bundle.js',

Github

https://github.com/lilonghe/demo---react-router4-mobx3/commit/9cfc62a3ec6a1732d291f221d2501c15d80610a1

结语

慢慢摸索呗~
webpack-bundle-analyzer可以分析打包后的 js 哦

[参考资料]

  1. https://reacttraining.com/react-router/web/guides/code-splitting
  2. https://webpack.js.org/guides/code-splitting-async/

本文链接:https://note.lilonghe.net//post/webpack-2-code-split-react-router-4-lazyload.html

-- EOF --