Ad

Code Splitting Application Sections Via Dynamic Imports

I'm trying to split my application into chunks using dynamic imports. As far as I've seen, I'm only able to use dynamic import for each component, but I'd like to split separate application sections into chunks:

  • Product section (multiple pages, stores, utils, etc.)
  • User section (multiple pages, stores, utils, etc.)

So if user access any route from product section, e.g. /product/:id, product.chunk.js would be loaded.

I couldn't find any examples of this so I'm not sure if it's even possible.

Ad

Answer

I'm not sure if mobx-state-router supports it, but what you really want here is nested routing. Maybe this will help you find a solution..

eg

main router

const Products = React.lazy(() => import('./products'));
const Users = React.lazy(() => import('./users'));
...
<Route path="/products" component={Products} />
<Route path="/users" component={Users} />

Then each section has it's own internal router..

products router (in products.jsx)

import ProductList from "./product-list";
import Product from "./product";

const ProductsAdmin = React.lazy(() => import('./products-admin'));

<Route path="/products" component={ProductList} />
<Route path="/products/:id" component={Product} />
<Route path="/products/admin" component={ProductsAdmin} />

users router (in users.jsx)

import UserList from "./user-list";
import User from "./user";

<Route path="/users" component={UserList} />
<Route path="/users/:id" component={User} />

You can then decide to lazy-load whole sections, or further split the bundles by lazy-loading deeper routes as well.

Ad
source: stackoverflow.com
Ad