We are developing a webapp, with uses quite a large API, which is included as npm library. The library has a lot of methods, which are not used in the applicaiton and our assumption was, that these methods are not included in the production build. However a check, for a specific method, which is not used in the application is still included in the production build.
Example:
Generated production build:
which is not used in the application:
Why is it not tree-shaken away and is there a way to tree-shake it? (e.g. with a stricter setting)
Tree shaking manages service code by looking at the import paths. If it’s imported, the tree shaker assumes that it is being used in the application.
Eg. When we inject service in @NgModule, we mention the service in import and hence this is dropped and considered as used entity by tree shaker
@NgModule({
imports: [],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [SomeService]
});
If we inject service using @Injectable's 'providedIn', service will be injected only when the module asks for it, if not, it will be removed by treeshaker. With 'providedIn' we can tell Angular which module to register our service to.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SomeService{
constructor() {}
}