Search code examples
webpack-2react-router-v4react-router-dom

Code Splitting by using react router v4


In react router v3 i have implemented the code splitting using System.import, Now i want to upgrade my app to react-router-v4 but the problem is that i am unable to split my code.

My routes.js file

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);
      }
    },
  }]
};

and then i just imported the routes in my index.js file and rendered them to rootNode like

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

Solution

  • Did it by simply adding routes like

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

    Never forget to use the CommonsChunkPlugin in your webpack.js