providedIn: 'root' service instantiates multiple times across lazy-loaded chunks
0 reputation · 03 Jan 2024, 23:06 UTC
Diagnosing duplicate root-provided service instances
A service decorated with providedIn: 'root' should resolve to a single instance within the root EnvironmentInjector tree. In a standalone Angular 17+ application using loadComponent() for lazy routes, the same service class appears in multiple lazy chunks after production build, causing separate constructor executions per chunk.
The build tool (esbuild or webpack) duplicates the service class definition across code-split bundles despite tree-shaking guarantees. This defeats the singleton contract of providedIn: 'root' without any explicit provider override in component or route configuration.
Bundle analysis confirms the service class exists in more than one chunk. Angular DevTools injector graph shows the service registered under different EnvironmentInjector nodes corresponding to each lazy route.
Questions
- Which build-tool configuration changes reliably prevent class duplication for
providedIn: 'root'services across lazy chunks? - Can
sideEffects: falsein package.json or explicit entry-point exports guarantee single-chunk emission for such services? - Does migrating the service to a separate library entry point with its own
ngPackageconfiguration eliminate the duplication?