2017-07-01 48 views
1

在反應路由器v3我已經實現了代碼分裂使用System.import,現在我想升級我的應用程序react-router-v4,但問題是,我無法分割我的代碼。使用反應路由器v4代碼分裂

routes.js文件

function errorLoading(error) { 
    throw new Error(`Dynamic page loading failed: ${error}`); 
} 

function loadRoute(cb) { 
    return module => cb(null, module.default); 
} 

module.exports = { 
    path: '/', 
    indexRoute: { 
    getComponent(location, cb) { 
     System.import('../pages/IndexPage') 
     .then(loadRoute(cb)) 
     .catch(errorLoading); 
    } 
    }, 
    childRoutes: [{ 
    path: 'notifications', 
    indexRoute: { 
     getComponent(location, cb) { 
     System.import('../pages/NotificationPage') 
      .then(loadRoute(cb)) 
      .catch(errorLoading); 
     } 
    }, 
    }] 
}; 

,然後我剛剛導入的路線在我index.js文件,並將它們呈現給根節點像

ReactDOM.render(
    <AppContainer> 
    <ApolloProvider store={store} client={client}> 
     <Router 
     history={browserHistory} 
     routes={routes} 
     /> 
    </ApolloProvider> 
    </AppContainer>, 
    rootNode 
); 

回答

0

它是否通過簡單地添加路由像

<Route 
  name="landing" 
  path="/" 
  getComponent={ 
    (_, cb) => import('./pages/LandingPage/LandingPage' /* webpackChunkName: 'landing' */) 
      .then((module) => cb(null, module.default)) 
      .catch((error) => cb(error, null)) 
  } 
</Route> 

永遠不要忘記你的webpack.js使用CommonsChunkPlugin:它爲我在我的hapi-react-hot-loader-example

import {asyncComponent} from 'react-async-component'; 

export default asyncComponent({ 
    name: 'AboutAsync', 
    serverMode: 'resolve', 
    resolve:() => import(/* webpackChunkName: "About" */ './About'), 
}); 

在路由器工作太棒了

0

如果你可以使用ES6動態進口,你可以去react-loadable並以這種方式實現代碼拆分:

export const AsyncComponent = Loadable({ 
    loader:() => import(/* webpackChunkName: "name" */ 'path/to/Component'), 
    loading:() => null 
}) 

// ... 
<Route path='some/path' component={AsyncComponent} /> 
1

結賬react-async-component

<Route 
    path="/about" 
    component={AboutAsync} 
/> 
+0

感謝codeBelt它的工作,我還發現了一個更好的溶膠而不使用任何外部軟件包 – sbs