I am building a Single Page App with React and I don't want to create a huge bundle and load it. Instead I would like to break it into smaller chunks and load them on specific routes on demand. What's the best way to do it in React or JavaScript in general?
Automatic code splitting is a great feature, I learnt something new today, thank you Somasundaram. :)
I'd like to highlight a simpler file-level approach, if you are not building something overly complex.
I have little to no idea on how you have structured your app; so what I say might probably be inapplicable to you. Having that said, I can imagine having different 'view' files for all the routes that you have in place, and have different corresponding scripts for these views (which you would obviously include in these view files).
If you have a main parent component that is common for all these views, have it in a different file and import it separately into all of the script files containing the child components pertaining to the corresponding view page.
At an abstract level, and to over simplify it a bit, the directory structure would be somewhat similar to this:
.
└───src
├───views
│ │ view111.jade
│ │ view112.jade
│ │ ...
├───components
│ │ mainComponent.jsx
│ │ view111.jsx
│ │ view112.jsx
│ │ ...
│ ...
│ ...
└───build
├───views
│ │ view111.html
│ │ view112.html
│ │ ...
├───components
│ │ view111.js
│ │ view112.js
│ │ ...
│ ...
│ README.md
│ ...
Somasundaram Ayyappan
If you are using webpack to bundle your code, you can use the code splitting feature.
This article explains how to do it with react router.