1

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
);
1
  • Here’s an awesome video tutorial with code samples that you can follow to set up code splitting with React Router 4+ youtu.be/j8NJc60H294 Commented Dec 20, 2019 at 17:08

3 Answers 3

2

Check out react-async-component. It has worked great for me on my hapi-react-hot-loader-example

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

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

In the Router:

<Route
    path="/about"
    component={AboutAsync}
/>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks codeBelt it worked and i also found a better solution without using any external package
0

If you can use ES6 dynamic imports, you could go for react-loadable and implement code-splitting this way:

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

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

Comments

0

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

1 Comment

Is this possible with the new webpack v4 that deprecates the CommonsChunkPlugin ? Or better said, how to do it with the new version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.