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.
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
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 namedfileReplacements
. In the defaultangular.json
file generated withng new
you can see that in the production environment (ng build --prod
) the filesrc/environments/environment.prod.ts
is included instead ofsrc/environments/environment.ts
. You can expand this to do additional replacements as needed.In angular this is the closest you can get to the equivalent of a preprocessor directive in c# AFAIK.