Codementor Events

Angular – Clear All of Your Console Logs in Production Build with Just a Few Lines of Code

Published Oct 20, 2017
Angular – Clear All of Your Console Logs in Production Build with Just a Few Lines of Code

When you were developing an application, you probably inserted a lot of console.log statements everywhere in your code. Sometimes you display information that your users are not supposed to see, but you think that you're good because most users will not press F12 (most of the time).

Not only it this a bad practice, you are also being lazy.

I will show you a trick where you can retain all of your console log statements, when in development mode, and clear all of it when in production mode.

Go to your main.ts file and add this:

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

Now you have a clean console log when you build your app for production.

Note:
In case you don’t know how to build for production, here’s the command

 ng build --prod

Thanks for reading and you don't need to be ashamed of your log statements 😃

Discover and read more posts from Brian
get started
post comments10Replies
santhosh raju
6 years ago

is it possible to the same thing in angular universal ssr. i followed your tutorial console logs are not printing in the browser console but those are printing in server console is there any way to stop in server console

Brian
6 years ago

you have to override the console.log in the server side too

Paul Lan - Learning - Read - Dev
6 years ago

Well, console.log could be stripped in ng compiler in compilation time.

  • It will reduce code base size.
  • It will leave ng global intact (keep in mind that Angular is not just for browsers)
  • Reduce CPU effort on running the placeholder function

Refer to: https://stackoverflow.com/a/43123545/7098927

Alessandro Aprile
5 years ago

not exactly: as in (this comment)[https://stackoverflow.com/questions/42307317/stripping-all-comments-and-console-logs-with-ng-build-prod-possible/43123545#comment76277801_43123545] --fix cannot strip console.log line directly (tested in ng6). So it’s equivalent to a search in editor, and need a manual search&replace anyway

msalehi@astound.net
6 years ago

To make it more interesting, you can have a service that gives you flexibility to control anything on the console log. take a look at https://smart-console.stackblitz.io/

Brian
6 years ago

that’s a nice library you got there

Show more replies