Show console outputs based on environment

ยท

4 min read

A project can be beautiful from the outside, but if the browser console is full of messy outputs it will immediately seem confusing and carelessly ๐Ÿ˜…

Using the local storange + custom script

In this script we:

  • assign the window.console to a custom variable named consoleWrap
  • create a "state" variable devMode and save it in the browser local storage. We will use it to determinate if we are in development or production mode!
  • instead of use the default console.log() function, use the new consoleWrap.debug.log() instead, as it will be shown in browser console only when devMode local storage var is 'true'.
// main.js

let consoleWrap = {};

if (localStorage.devMode && localStorage.devMode === 'true') {
  consoleWrap.debug = window.console
} else {
  consoleWrap.debug = () => {}
}
// other-file.js

consoleWrap.debug.log('Hello!')

To set the devMode in browser local storage, please add this line in browser console:

// browser console

localStorage.devMode = 'true'

> Hello!

๐Ÿงจ !important

local storage values are strings ๐Ÿคญ, so we have to assign the variable as string localStorage.devMode = 'true' and check its value as string localStorage.devMode === 'true'.

Using vue env + webpack + loglevel

In a Vue project we already have webpack installed, and do not output noisy console.log() in production JS bundle is an efficient way to save kilobytes! ๐Ÿ˜

Loglevel to the rescue!

Minimal lightweight simple logging for JavaScript. loglevel replaces console.log() and friends with level-based logging and filtering, with none of console's downsides.

Install it in development packages:

npm install loglevel --save-dev

In every JS file we would need to output something, we have to:

  • import loglevel
  • use its syntax, where log.debug == console.log
import log from 'loglevel';

log.debug('This output will be in both development and production mode')

Why did we talk about webpack above? ๐Ÿ˜…

Well, webpack will not add into the JS bundle the code that will never be executed, as for example a condition that will never match:

if ((2 + 2) === 5) {
  // This code will never see the sunlight! ๐Ÿ˜ข
}

so if we use node ENV variables settings:

# .env

VUE_APP_DEBUG=true
# .env.production

VUE_APP_DEBUG=false

we can add all console outputs we want to our project

import log from 'loglevel';

if (process.env.VUE_APP_DEBUG) {
  log.debug('This output will be in development mode, but not in production mode')
}

and none of them will output in the final JS bundle! ๐ŸŽ‰