Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude components code from production environment in Angular

I would like to exclude certain components from my production build in Angular 5+. So far I have read around and I understand the concepts of environment variables, but to my understanding those are available at runtime. What I am looking for is to actually exclude certain modules from ever being imported so that the code for them does not get to the production build (files).

I also dont want to have an <div *ngIf="isProduction">...</div> laying around, what I would rather want to do is something like this:

Component({ ... templateUrl: environment.production ? 'app.prod.html' : 'app.html' })

However this is also not possible due to how the Angular compiler works.

I guess the answer to this is to tweak the angular-cli, but given there is no good documentation (that I can find), I'd like to know if someone perhaps has a better idea?

like image 882
Max101 Avatar asked Apr 04 '18 08:04

Max101


1 Answers

For those looking for a *not so scalable* solution.

Solution is for Angular 5 / Angular 6+

You can switch specific files depending on what environment you are building/serving by adding each file pair in the angular.json file.

For example, if you wish to use app.prod.html instead of app.html in your app component only when using the production environment / configuration.

In angular.json add your replacments in the fileReplacements array under the config you wish to have replaced:

{
  ...
  "projects": {
    ...
    "configurations": {
      "production": {
        ...
        "fileReplacements": [
          ...
          *** ADD YOUR REPLACEMENT FILES HERE ***
          ...
        ]
      }
    }
  }
}

Using the above example:

{
  ...
  "projects": {
    ...
    "configurations": {
      "production": {
        ...
        "fileReplacements": [
          ...
          {
            "replace": "src/app/app.html",
            "with": "src/app/app.prod.html"
          }
          ...
        ]
      }
    }
  }
}

Not a pretty solution as it seems you will be doing this for each file you wish to replace but it should work nontheless.


Build or serve the specific config with

ng serve --configuration=production
ng build --configuration=production
like image 66
Matthew Mullin Avatar answered Nov 01 '22 08:11

Matthew Mullin