Search code examples
javascriptangulartypescripttree-shaking

Conditional environment variables tree-shaking


Currently I am trying to remove unused code based on the environment variable. In the code below when I run ng build --prod and set evironment.showDevTools = false in environment.prod.ts then I expect the console.log not to be included in the final build file, but unfortunately it is. What am I doing wrong?

import { Component } from '@angular/core';
import { environment } from '../environments/environment';

if (environment.showDevTools) {
  console.log('showing dev-tools');
}

@Component({
  selector: 'app-component',
  templateUrl: './app.html',
  styleUrls: ['app.scss']
})
export class AppComponent {

}

Part of main.js

,ut=n("AytR");ut.a.showDevTools&&console.log("showing dev-tools");var st=function(){

Solution

  • I had to add a field called "sideEffects": false to the package.json. So it currently looks like this:

    {
      "name": "myApp",
      "version": "1.0.0",
      "sideEffects": false,
      "scripts": {
        "ng": "ng",
        "test": "ng test",
        ...
      },
    }
    

    References: https://webpack.js.org/guides/tree-shaking/, https://github.com/stereobooster/package.json#sideeffects