How to split your apps by routes with Webpack

Initial state

To imitate routing system in our example app, I will use Backbone Router — very popular, powerful, and simple to work with solution to the single-page apps routing problem. But this approach will suffice any router, even home-brewed, it just needs to be able to handle missing routes and to refresh the page.

  • Very important page that users are visiting very often
  • About page, with tons of graphics
  • Some heavy, complex part of your app. It is very powerful, but users do not use it every time while visiting your site. Or maybe it is available only for paying users
./src/router.js
./src/index.js

Apps extraction

Before we touch a webpack config, we need to split our code into separate logical modules with their own smaller routers:

./src/apps/about/router.js
./src/apps/heavy/router.js
`./src/apps/about/index.js` and `./src/apps/heavy/index.js`
./src/index.js
./src/router.js
./src/index.js

Loading apps depending on a route

Even if our app is fully split and bundles are loading asynchronously, we’re still loading everything on the main page, not on-demand. Let’s go ahead and change this.

./src/app_finder.js
./src/router.js
require(‘./apps/’ + mini_app_name + ‘/index.js’).default;
./src/apps ^\.\/.*\/index\.js$
./src/router.js
./src/router.js

Making everything better

Theoretically, we can stop now: we have the main app and 2 mini apps, which are loaded asynchronously if we hit a route which they can handle. But let’s step aside and think what should the next developer do to add a new mini app:

  • describe routes and app’s logic
  • copy app’s routes into AppFinder’s custom_apps_routes constant
Routes extraction for About mini app
./src/router.js
  • describe routes in the routes.js and app’s logic
  • Create metadata.js that exposes an object with app’s name and routes

Let’s sum up

Now we have an app that is better and lighter for a user, but almost the same (or even better structured) for a developer.

--

--

code, coffee, drums, neuroscience

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ilya Zayats

Ilya Zayats

code, coffee, drums, neuroscience