0

My app has a simple Logger service.

@Injectable({
  providedIn: 'root'
})
export class Logger {
  log() {
    console.log()
  }
}

The service is injected in other services and components in the app.

Inspecting the production build output I see many calls to logger.log() which is increasing the bundle size.

I only need the Logger in dev environment. How do I completely remove the Logger service, and all log() function calls from the production build output?

Rafff
  • 1,510
  • 3
  • 19
  • 38

1 Answers1

0

Instead of adding a logger to all your services, you could potentially use an interceptor as an in between for all your services.

logger.interceptor.ts

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable()
export class LoggerInterceptor implements HttpInterceptor {

  constructor() {
  }

  /**
   * @param {HttpRequest<any>} req
   * @param {HttpHandler} next
   * @returns {Observable<HttpEvent<any>>}
   */
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(req);
  }
}

Then following this example you can use the useFacotry (or possibly even the useClass in the same way) in your app.module.ts to switch between what you import. This is untested code so you may have to play with it a little to get it to work.

app.module.ts

import {LoggerInterceptor} from './path/to/realm.interceptor';
import {environment} from './environments/environment';

...

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      multi: true,
      useClass: () => {
        if (!environment.production) {
          return new loggerService();
        }
      }
    },
]
rhavelka
  • 2,283
  • 3
  • 22
  • 36
  • Thanks. This is actually what I did for the first time when I started to think about it. The problem is kind of solved because the console doesn't show logs anymore. As you said, every piece of code (this.logger.log()) which is in many components and services will be still included in the bundle. – Rafff Oct 26 '18 at 14:28
  • you might be able to do something with an interceptor... then exclude the interceptor on the production build.. I will try to figure something out and then update my answer if I find anything. – rhavelka Oct 26 '18 at 14:55
  • @Rafff I updated my answer (a third time, I don't know if you saw the second) and something like this should work. you may have to play with it a little though. – rhavelka Oct 26 '18 at 16:04