I have a SharedModule
and I stuff every component that needs to be included in more than one module in there.
But not every module needs every component that is exported from the SharedModule
.
If I don't use a component in my template or via an import
statement, is this component still included in the final bundle or is it removed via tree shaking?
The answer would be obvious to me if the components were only ever referenced via an import
, but is the build process "smart" enough to know if a component has been used in the template or not, and remove tree shake it if isn't?
If it's not smart enough, then it means that I have to create many different smaller modules that include only the relevant components.
There is this question: Angular Module tree-shaking, but the answers are old and valid only for Angular 8-.
Yes, unused components can be removed components by tree-shaking.
But better than just believing some random guy on SO, I'd recommand you to check by yourself by running
NG_BUILD_MANGLE=0 ng build
NG_BUILD_MANGLE=0
disables the mangling part of the build so the class names are retained. Once your build is done, check your main bundle and you'll see which components are defined (or not).If your
SharedModule
is part of a library and it involves a barrel file, this would likely break the tree shaking. This is a known limitation on both builders (webpack and esbuild).To mitigate this, library like
@angular/material
rely on several subentries. (@angular/material/button
,@angular/material/icon
etc.).