Is there a #define in angular?

360 views Asked by At

Is there any way to achieve the #define functionality with Angular?

I'm talking about the ability to add/remove some code based on defines at compile time, just like C++,C# and other lower level programming languages do.

2

There are 2 answers

1
Igor On BEST ANSWER

It is not possible in the exact same manner as a preprocessor directive in c#. However, I assume you are wanting to do this at the time the js bundles are generated. What you can do is specify different files to include based on environment settings but there is not a way to omit only part of the code in the same file.

See the angular.json file and sections named fileReplacements. In the default angular.json file generated with ng new you can see that in the production environment (ng build --prod) the file src/environments/environment.prod.ts is included instead of src/environments/environment.ts. You can expand this to do additional replacements as needed.

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

In angular this is the closest you can get to the equivalent of a preprocessor directive in c# AFAIK.

4
zos1000 On

You do not need a plugin, you can use angular native optimization.

import { environment } from '../environments/environment';

if (environment.production) {
    console.log('@@@ environment.production @@@');
} else {
    console.log('@@@ NOT environment.production @@@');
}

when you run 'ng build --prod' only the statement within the first condition will be included in the bundle, without the if statement.

Here the bundle screenshot, I highlighted the generated component code