1

Now I am using react-route to control my routes!

You know I tried to build a single page app. There is only one entry file named index.js

When index.js is too heavy loading time will very long. Maybe 10000ms.

But there are many routes why must loaded them all first? If I can lazyload route not only child routes.

When I go to admin route it will load js file of admin and about will load js file of about , can I?

webpack bundle will have two files [name].js and come.js. But it too heavy.

Anyone meet the same problem?

1 Answer 1

3

You can do lazy loading of React Components with react-router in two ways.

Webpack's require.ensure way When you go with this approach, you would be dealing with the react router object something like this,

childRoutes:[
    {
      path:"/pageone",
      getComponents:(a, cb) => require.ensure([], require => {cb(null, require("pages/PageOne"));})
    },
    {
      path:"/pagetwo",
      getComponents:(a, cb) => require.ensure([], require => {cb(null, require("pages/PageTwo"));})
    }
  ]

Webpack's bundle-loader way When you go with this approach, you would be dealing with the webpack loaders option.

module: {
  loaders: [{
    test: /.*/,
    include: [path.resolve(__dirname, 'pages/admin')],
    loader: 'bundle?lazy&name=admin'
   }]
}

You can find an example from react-router which uses bundle-loader and here is a nice blog about lazy-loading with bundle-loader and here is a blog with require.ensure

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried to use this way getComponent={(nextState, cb)=>{cb(null, require('./components/menu/MenuComboMain.react').default)}} on Route element Does this way have some advantages and disadvantages compare with yours
just require will bundle all the modules at one shot. require.ensure will create separate files to lazy load the modules

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.