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 a 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 { };
    }
  }
}

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:

export class AppComponent {

  constructor(private consoleToggleService: ConsoleToggleService) {

    this.consoleToggleService.disableConsoleInProduction();

  }
}

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s