Unused Injectable services with providedIn: 'root' are Included in main.js, increasing bundle...

Discussão em 'Angular' iniciado por Sasha, Dezembro 29, 2024.

  1. Sasha

    Sasha Guest

    Issue:

    In an Angular 19 standalone application, I have an API client file containing over 100 @Injectable services, each marked with providedIn: 'root'. However, only 3–4 of these services are used in the app. The problem is that all unused services are still included in the production build (main.js), significantly increasing the bundle size.

    Details:

    I’m building a new Angular app using the full standalone approach (Angular 19). I also have another app built with Angular 17 that follows the traditional NgModule-based approach. Both apps use identical API clients generated via NSwag Studio, which creates multiple @Injectable services like this:

    @Injectable({
    providedIn: 'root'
    })
    export class FeatureClient {}


    In the modular app (Angular 17): Unused services are excluded from the final bundle (tree-shaking works as expected). Used services are included in main.js only when explicitly injected.

    In the standalone app (Angular 19): All services from the API client are included in main.js, regardless of whether they are used or injected.

    Manually removing any unused code from the API client obviously decreases the bundle size. To further verify that's the case for both apps I did the following:

    1. Add a mock service to the API client file.
    2. Build the application for production.
    3. Check if the mock service is present in the final bundle (main.js).
    4. Inject the mock service in a component, rebuild, and verify the output again.

    Results:

    Modular app: f the service is not used, it is excluded from the bundle. If the service is injected, it is included in main.js.

    Standalone app: included in both scenarios regardless of the injection.

    Continue reading...

Compartilhe esta Página