I am building a new project using Angular v13. I had a query regarding bundle size and optimization in Angular.
Suppose I have 4 Components
Component A
Component B
Component C
Component D
All of these are lazy loaded with individual modules and routes.
Now I have shared module where I am keeping all the reusable component all together.
Shared Module
Reusable Component A
Reusable Component B
Reusable Component C
Reusable Component D
So all these components are referred in one module. So my question is lets just I need to use the reusable components in two of the components. But I don't need all the reusable component in these components. For Example
Component A -> Imports Shared Module -> Uses Reusable Component C
Component C -> Imports Shared Module -> Uses Reusable Component D
So since I am importing the shared module which means all the reusable components will be available but I am using only one. So will it affect my production bundle? or Will it affect my application performance? Will Angular handle internally and remove the unnecessary components which aren't needed in that specific lazy loaded component/routes?
The way I am maintaining shared module, is it the right way? Are there any better approach for this?
CodePudding user response:
Each lazy loaded module (not component!) creates its own javascript file, which is lazy loaded if one of the components is used. One your application loads this module with those 4 components, the loading stops and all 4 components can be created.
So from the loading part, every lazy loaded "module" is a question of network optimization. If you don't need the components in it at the beginning of your app, you can outsource them in such a module.
Performance trade off is the loading part, but once loaded, the module behaves like a normal module. So perfomance around interacting with those components is not affected.
CodePudding user response:
Although you import the entire SharedModule in each lazy loaded module, if you inspect the output bundles you will see that angular create especific bundle for each combination of modules, like modulea-moduleb-shared.bundle.js, modulea-moduleb-shared.bundles.js.
This means that in practice angular don't create a bundle for the entire shared module, with all the components, instead of that it creates a specific bundle with the exclusive components shared between two lazy loaded modules. So, you don't have to worry about components in SharedModule used in module A and B, but not in C, for example.
You can gain more insights about your final bundles and the content of each one, using weback-bundle-analyzer (in case you don't know it): https://www.digitalocean.com/community/tutorials/angular-angular-webpack-bundle-analyzer.
