简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM