Reputation: 147
I just wondering let's say I already have a website. If I would like to inject some react modules into it lets say MODULE-A, MODULE-B, MODULE-C. At some situations, MODULE-A and MODULE-B are on the same page. All modules are sharing react
, axios
but also they have their own dependencies. what is actually the best approach to prepare build for it?? I actually like create-react-app
. Is there any smart way to make modules only load required dependencies? so I can include them separately and if both exist on the page they will not clone dependency in code.
I want to avoid the situation that I have 20 small modules and all of them use react inside built code. So 60% of the code will be duplicated dependencies.
Upvotes: 1
Views: 1070
Reputation: 11
I dont know answer for React but for the future, maybe you can think about using Angular instead, and its ngModule capability into splitting application to multiple independent modules with their own dependences.
https://angular.io/guide/ngmodules
Upvotes: 0
Reputation: 2983
You have not many options
You can leverage code-splitting as referred here https://webpack.js.org/guides/code-splitting/ so let's say you have
ModuleA -> [depA, depB, depC]
ModuleB -> [depA]
ModuleC -> [depC]
now you can code split to 4 javascript files which will be
moduleAbundle.js
mobuleBbundle.js
mobuleCbundle.js
vendors.js
vedors will be concatenation of depA, depB, depC
but ofcourse when you will load moduleB and ModuleC on 1 page you will be also loading depB as it's included in vendors.js
you will need to think and play a lot with orchestration of this.
But what you can actually do you can think of most critical parts and most shared deps and list them, let's say all of your packages are using react
, react-dom
, lodash
you will make bundle for vendors
with only those libraries, any other library will be bundled with module itself and yes you can't 100% elimate "double-loading" but if you will double load library which has several kB it's fine, when it's larger, ship it with vendors.js
or you can have some complex mechanism on backend side when you will exactly specify and orchestrate loaded dependencies because you know which modules are rendered and what are they dependencies. But there are no any ways of on-the-fly
bundling and sending only needed and requested dependencies, it would be very slow to do that on-the-fly and you need to flush quick response to the browser not slow it down with additional compilation process. So it's most likely a manual job to correctly prepare and split code in logical chunks which makes sense.
Upvotes: 2