Splitting React App To 2 Independent Parts

- 1 answer

The app I'm developing (Node.js + Express + React + Alt) is addressed to 2 types of crowds - Teachers, for which it is a large app with multiple routes, and students, for which it is a very small app with a single route.

I want to separate these 2 parts completely, so the code of teachers part won't be loaded when students route is rendered.

I have two reasons in mind:

  1. Better loading times for students' app - There's no point in downloading and running that big chunk of JavaScript when I know it won't be needed.
  2. Security Aspect - Although there's no data exposure, I'd still rather hide the code the teachers use from the students.

Is there an easy way to do this?
Can I use one React app (And one React-Router)?

Thanks for any help!



The best way to implement this is using the Webpack feature Code Spliting. This allow you automatically split your code in chunks and only load the require code when is needed.

You can see the React Router example: huge-apps

The magic happen in the internal components (require('./routes/*')), here they use the callback method to get the components and look something like this:

export default {
  path: 'nameOfComponent',
  getComponent(location, cb) {
    require.ensure([], (require) => {
      cb(null, require('./components/nameOfComponent'))

Require.ensure is detected by Webpack and generate a new chunk with all the code and his internal dependencies.

When the application is executed in the browser the first load only get the main chunk with the routes definition, and each router components is loaded on demand (when you change of route).

For me, this is the most clean way to do it. Because you delegate the responsibility to the build system. In Webpack 2, you could use System.import instead of require.ensure, and is a more ES6 standard.