在React

时间:2017-02-17 13:52:25

标签: reactjs webpack react-router code-splitting

是否可以使用System.import实现嵌套异步路由获取,因此应用程序只分为几个合理的块,而不是许多小块?

背景

我在我的React应用程序中实现捆绑拆分的过程。 最初我实现了bundle-loader(我无法在所有情况下都能工作),然后使用System.import,我发现它的行为更加可预测。

问题

代码分割在路由的基础上工作得很好,但是,它产生了许多小捆绑,并且额外捆绑和获取的开销是不必要和浪费的。

作为一个例子,我有这个代码,当你导航到他们的页面时加载仪表板,设置或图像的包:

    <Provider store={store}>
        <Router history={browserHistory}>
            <Route path='/' component={Container}>
            <IndexRedirect to="Login" />
            <Route path='Registration' component={RegistrationContainer} />
            <Route path='Login' component={LoginContainer} />
            <Route path='Route1' >
                <IndexRedirect to="Dashboard" />
                <Route path='Settings' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Settings')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}/>
                <Route path='Dashboard' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Dashboard')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}
                    />
                <Route path='Images' 
                        getComponent={ (loc, cb)=> {System.import('./components/Route1/Images')
                                              .then(loadRoute(cb))
                                              .catch(errorLoading); }}
                    />
        </Router>
    </Provider>

首次导航到Route1路径时,是否可以加载所有三个捆绑包?

非常感谢

1 个答案:

答案 0 :(得分:2)

我玩过并设法找到一个解决方案,将任何给定数量的子路由的get请求数减少到2个。

我得到这个结果的方法是向Route1引入一个索引组件

<Route path='Patient' getComponent={ (loc, cb)=> {System.import('./components/Route1Index')
            .then(loadRoute(cb))
            .catch(errorLoading); }}>

然后我创建了索引组件,其中包含所有子路由的导入,如下所示:

import React from 'react';

// Child route components
  import Settings from './Settings';
  import Dashboard from './Dashboard';
  import Images from './Images';

export default (props) =>(
  <div>
        {props.children}
  </div>
)

我还在Webpack minChunks:2

中设置了CommonsChunkPlugin

现在,当我导航到Route1的任何子路径时,只加载了2个包:Route1Index包和包含所有导入的包

相关问题