Search code examples
angularangular-moduleangular-standalone-componentsangular-builder

Exclude standalone components depending on a build in Angular


I have two environments - one for testing and the second for the release. I have a standalone component that helps me with debugging, but I don't want to include this in the release build. How can I exclude it? I mean, my goal is not to hide it(behind any *ngIf flag) but completely remove it from the build.


Solution

  • Two possible ways:

    1. Deferrable Views

    You can use the deferrable views feature of Angular (https://angular.io/guide/defer).

    You would be able to define something like:

    @defer (when debugMode) {
      <your-component />
    }
    

    Where debugMode is you environment variable.

    This is basically a lazy loading feature for components.

    1. TsConfig File Exclude

    you can actually exclude file from Angular build in the tsconfig.json:

    "exclude": [
        "path/to/your/file.ts"
    ]
    

    To use this you may want to have one tsconfig.json for the "production" build and one for the "debug" build that doesn't exclude the file.

    Than update the angular.json to use the right tsconfig file for the build:

    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      },
      {
        "replace": "src/yourconfig.ts",
        "with": "src/yourconfig.prod.ts"
      }
    ],