简体   繁体   中英

Dynamic importing component in react router

I want to split the bundle based on routes. So tried with dynamic importing in react-router as shown below, but no luck. Also tried the same with loadable, in loadable there is flickering when hydrate starts. It removed entire dom and added again. How to acheive this?, i dont want to bundle everything in a single file, similarly i have 10 different routes.

// With dynamic import
const routes = [
{
 path: '/details/:name/:id',
 component: import(/* webpackChunkName: "details" */ '../components/details')
}
];
// With Loadable
const Details = loadable(() => import('../components/details'), { ssr: true });
const routes = [
  {
    path: '/details/:name/:id',
    component: Details
  }
];```

Instead of using component prop in Route , you might use render prop which takes a function, and therefore allow you to implement some logic inside

const routes = [
{
 path: '/details/:name/:id',
 render: () => condition ? import(/* webpackChunkName: "details" */ '../components/details') : import(/* webpackChunkName: "component2" */ '../components/component2')
}
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM