Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Does importing unnecessary ngModules increase file size if they have been imported elsewhere?

I'm working with a rather large Angular application and currently have all shared components and modules inside a Shared Module which I import whenever I need anything which it exports.

However I have some small feature-modules which only needs very few modules from the Shared Module, should I then increase the complexity and modularity of the architecture in order to just import the modules I need, even if they are imported elsewhere?

The Angular docs state that imported modules which have already been imported in another module is cached and not a problem, but what does that mean, does the app gets slower/bigger even so?

Example: Module 1 imports A, B, C. Module 2 imports A, C, D.

Is there a performance loss if I import A, B, C, D in both modules (e.g through a Shared module)?

like image 294
Jakob Segerslätt Avatar asked Oct 18 '17 06:10

Jakob Segerslätt


1 Answers

Maybe. It depends on your app's structure.

If you're not using lazy-loading, you can follow the docs and it will not duplicate any code. The default chunks created with the original config's built of the angular-cli will produce a single scripts.bundle.js for your modules (among other chunks for other stuff).

Now, if you are using lazy-loading (as you said you are in the comments of your question), it will create a chunk for each lazy-loaded module and you should proceed with caution.

The angular-cli uses webpack to create these chunks and by the time of this comment, it will duplicate the imported modules (and 3rd party libraries!) on EVERY chunk that needs them.

This is a known issue and it has been partially addressed, but it's waiting for webpack to implement a feature that's needed to solve it.

Suggestion:

Create a SharedModule for each of your lazy-laoaded modules and import/declare only the things necessary for that module and use only this SharedModule. Do not import your main app's SharedModule from within a lazy-loaded module.

This will still duplicate modules needed by different chunks, but at least it won't add unnecessary modules where they are not needed.

And keep an eye on the issues linked above, so you know when you'd be able to avoid this workaround.

Cheers!

like image 139
mattarau Avatar answered Sep 29 '22 11:09

mattarau