Meteor 1.5 and Code Splitting with React and React Router

Meteor 1.5 is out and we can finally do code splitting!  If you are not familiar with code splitting, this allows us to separate our logic in a single page web app (SPA) and only send the client the relevant portions of code. This is useful in a couple immediate ways:

  1. You have a giant application that is too large to send at once (any script files over 1MB often take too long and the user experience is terrible)
  2. You want to keep some portions of code hidden until the user is authorized to see it

We are going to cover option 2 since that is a use case I just ran into. Sometimes splitting the code up can make the files larger (or the same size) so Meteor has provided a nice tool that helps visual how large the file sizes are once they are bundled. You can read more about that in this great post: Bundle Visualizer. Use the tool before the split, and after the split to make sure it doesn’t effect your code in the wrong way (compare the two).

I am going to show the use of React with React Router 4 and how to split out an admin section of your code.

Here is a component called “AdminPage”. This loads when the user tries to connect to /admin/home which is the portal for all things admin. AdminPage is in our main app code base, and in the top level React Routes. So once someone hits /admin/home, this component is called (and it’s always sent to the client since we need something for them to code split!). I am not showing that route here for brevity.

Here is our Admin Route that we are importing, which includes the admin pages (not going to show those here, they can be anything you want):

That’s the deal, not too complicated once the syntax is learned. The odd part is swapping the components around for React.

There are many others ways to use this, for restricting admin pages this is the one I found to work the best.

Also note that the code that is split gets sent down through DDP within meteor (the distributed data protocol – the always on connection), not through a new http request and bundle like webpack does.

Leave a Comment