DEV Community

Dhananjay Kumar
Dhananjay Kumar

Posted on

The simplest way to disable console.log for Production build in Angular?

I work with different developers, and most of them rely on console.log () or other console methods for development. They use the console to print various values to debug while doing the development. I call this approach console-driven development. Cool name, right?

These console functions become overwhelming in production as users can see many things printed in the browser console, which they may or may not understand. Sometimes a junior developer can leave something significant on the console that may cause a potential security risk.

So, we must not have the console in the productions. There are various ways you can disable console in the production, such as:

  1. By using libraries such as logger
  2. Creating a linting rule that if code contains any console function, the build fails
  3. Or you are writing a simple service to perform this task for you.

In this post, let us see how we can create service to disable the console in the production step-by-step.

Add service to the project. I am calling it as ConsoleToogleService. In the service, we make all the console functions void. So service should look like the below:

import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})
export class ConsoleToggleService {

  constructor() { 

  }

  disableConsoleInProduction(): void {
    if(environment.production){
      console.warn(`🚨 Console output is disabled on production!`);
      console.log = function():void{}; 
      console.debug = function():void{};
      console.warn = function():void{};
      console.info = function():void{};
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

In the service, you can see a function called disableConsoleInProduction(). Inside this function, we are making all the console functions void. It is as simple as this.

Now in the AppComponent, inject this service and call the function in the constructor as shown below:

  constructor(private consoleToggleService : ConsoleToggleService){

    this.consoleToggleService.disableConsoleInProduction();

  }

Enter fullscreen mode Exit fullscreen mode

When you build an application for production, you won’t have any console. However, the development console will work as usual.
I hope you find this post helpful. Thanks for reading.

Top comments (0)