Ole
Ole

Reputation: 47212

Tree shaking for libraries in Angular 8

I'm planning on making a standalone Angular service for Angular 8+, and I've been reading up on how to make it tree tree-shakable.

I believe all we need to do is this:

@Injectable({
  providedIn: 'root',
  useFactory: () => new Service('dependency'),
})
export class Service {
  constructor(private dep: string) {
  }
}

As this tells Angular how to construct the service.

Is this all we need to do? I've seen other NPM modules like this one use ModuleWithProviders like this:

 export class Module {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: Module,
      providers: [
        StripeScriptTag
      ],
    }
  }

I assume that this is not necessary because the providers array still does not describe how to instantiate the service.

Upvotes: 0

Views: 1209

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21658

All you need is the

providedIn: 'root'

Services that are provided in root are tree shakeable. If it is provided in the root then you get the same singleton instance in the entire application. You only need to add it to a providers array if you want a new instance of the service across your module instead of the global singleton instance.

Upvotes: 2

Related Questions