In Part I Post, I shown before and after performance report of SaaS frontend app.
Main bundle size was reduced from 5mb to around 1.5mb ๐ฅณ by following below approaches.
Let us deep dive how we achieved it.
Code Splitting At Multiple Levels
React supports code splitting out of the box with React.lazy
.
๐ Don't load the code you don't need to
๐ Route Based Code Splitting
Route based code splitting means creating different chunk for each page. e.g. If user is visiting home page web browser will only request required JS bundle for home page.
๐ Lazy Load Third Party Libraries
Several third party libraries were added in main vendor chunk which wasn't required in initial load.
๐ We converted the imports to async/await which loaded libraries on demand.
Lazy loaded third party components with withLazyLoader
. It is the HOC wrapping React.lazy
which handles named exports as well.
๐ on Demand Redux/Redux-Sagas
Still there was lot of reducers/sagas code were present in main bundle. We dig further and figured it out as the app has one root reducer which is normally generated by combineReducers()
which was passed to createStore
. Similarly there is root Saga aggregates multiple Sagas to a single entry point for the sagaMiddleware to run. Unfortunately redux doesnโt offer a built-in API to on demand load reducers.
We came across the redux-dynamic-modules library. This library introduces the concept of a 'Redux Module', which is a bundle of Redux (reducers, middleware) that should be dynamically loaded.
It is not actively maintained by Microsoft team though stable enough to use in production.
โฅ๏ธ Don't forget to like, follow & share in your network if you are interested in frontend optimisation and want to make web better.
Stay tuned for next posts ๐
WebPack Optimisation-[ Part 3 ]
Bundle Analysis & Keep Bundle In Check -[ Part 4]
Top comments (0)