A while ago, I had a similar question and stumbled upon an article that really helped me out: Avoiding Common Confusions with Modules in Angular, written by Max Koretskyi aka Wizard
The Concept of Module Caching
Every now and then, a developer raises concerns on stackoverflow about the potential duplication of module code when importing it to both lazy and non-lazy modules. This assumption is quite common, but fret not as all existing module loaders have mechanisms in place to cache the modules they load.
When SystemJS loads a module, it stores it in the cache. Subsequent requests for this module will retrieve it from the cache rather than making another network request. This caching process occurs for each module.
For instance, when working with Angular components, you typically import the Component decorator from the angular/core module:
import { Component } from '@angular/core';
Despite referencing the same package multiple times in your application, SystemJS only loads the angular/core package once and caches it for future use.
A similar approach is taken by Webpack if you utilize angular-cli or configure webpack manually. The module code is included only once in a bundle and assigned an ID. Other modules then import symbols from this module using the assigned ID.
I highly recommend reading through the entire article and jotting down some personal notes as it greatly aided me in understanding Angular's architecture. The article is well-written and explains the concepts clearly, so there's no need for me to rephrase it.
On another note, a SharedModule is utilized for sharing components, pipes, and directives. While you may import modules from third-party libraries and export them for sharing, essentially, you are disseminating the components, pipes, and directives declared within the third-party lib's module (such as Angular Material's modules).
The SharedModule gets compiled into main-abcd1234.js
, somewhat resembling the compilation log seen midway through this post :
https://i.sstatic.net/oGMsW.png
The main-abcd1234.js file is loaded at the start of the app. You can confirm this by checking the network tab during your app's initial load.
In my current project, the size isn't too substantial, just a few hundred kilobytes. To test if your "app size" increases, try importing the SharedModule into a module X that uses only one component from the shared module and observe if module X's compiled bundle size changes. It likely won't.
If you're curious about how chunks are named, you can set namedChunks
to true in angular.json
and execute ng serve --prod
to avoid seeing encoded characters.
Cheers!