I have a huge application that I have written in reactjs and redux.
My question is how is, how do I reduce the page size? I know there is code splitting in webpack, but my understanding is that it is used for multi page apps. I just have one index.js
page.
What am I missing here. How do I have separate js files for different pages to reduce file size for a page, and also to reduce initial page load?
What you described would be best called commons split, in which you track the common dependencies for the many different pages of your app and put them all in a separate bundle.
There's a few ways in which you can benefit from bundle splitting in a SPA. The simplest one would be separating all vendor modules into a single bundle, so that when you change code in the main app, the user doesn't have to download dependencies again (e.g: jquery), because it's cached.
Example: your app uses React. But you changed something inside a component, not React itself. You build and deploy again. Your bundle file will be different (sometimes even with a new name hash). If you don't use some sort of vendor split technique, the user will have to download React again, albeit not having it changed.
The basic configuration would be using splitChunks
which added much more automation in comparison to old CommonsChunkPlugin
. So, a beginners way to take advantage of it would be having the following config in your Webpack production config:
const productionConfig = merge([
// ... other configs
{
optimization: {
splitChunks: {
chunks: "initial",
},
},
},
]);
If you want to dig into it and achieve more sophisticated, customized ends, you can make use of splitChunks
documentation here. One example would be using .cacheGroups option, and providing a regular expression to determine matching files for a given group.
const productionConfig = merge([
// ... other configs
{
optimization: {
splitChunks: {
chunks: "initial",
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
}
}
},
},
},
]);
Take a look at this guide for advanced guiding on the topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With