Angular, Development

How to Remove Console Log Messages from an Angular Application

Writing console log statements for debugging the application run time by developers are very common and often times we tend to remove the console log statements from the application that will gradually gets deployed to production.

This scenario mostly happens when there are a handful of developers who work on the same project but on different features/ bug fixes.

This post will help you remove the console log statements from any of the Angular based application. 

Refer, this post on how to remove console log messages from any application.

There is a small snippet of code that will suppress the console log messages from the deployed version of your application.

Instead of removing the console logs from each and every page of the Angular codebase, we can tell Angular, to process your code first to suppress the console log messages and then load it’s modules and components.

By default, all applications will have a main.ts file inside src folder.

Check out this if condition below in your main.ts file.

if (environment.production) {

Now, write the following snippet inside this condition that checks if the production environment is set to TRUE.

if(window) {
	window.console.log = function() {};

Your final code will look like this below.

In case you have multiple environments set up in the application, make sure to check the production property in your specific environment file object is set to TRUE. The above code will work if the production environment is set to TRUE.

There can be a bit of a situation that you may not have a main.ts file in your src folder. Such cases, make sure to check your angular.json file for the main property like the image below.

This will tell you the name and location of the file where you can put in the console.log suppressing snippet.

It’s suggested to put this code in the main.ts file as that is the first piece of code that gets executed when we compile and build the angular app ng serve or ng build prod

There are other options to have the console log suppressed using webpack, and for that to make it work, we may have to eject the webpack from the angular-cli which is kind of tedious as we will have to manage the webpack config, angular project configurations and the ng commands would stop working as we will have to manage the application without the help of the angular-cli.

I prefer to do this in the main.ts the cleaner way.

Let me know in comments on what worked out for you, when you had to work on such tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.