Show console outputs based on environment
2 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 namedconsoleWrap
- 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 newconsoleWrap.debug.log()
instead, as it will be shown in browser console only whendevMode
local storage var is'true'
.
// main.js
let consoleWrap = {};
if (localStorage.devMode && localStorage.devMode === 'true') {
consoleWrap = window.console
} else {
consoleWrap = () => {}
}
// other-file.js
consoleWrap.log('Hello!')
consoleWrap.error('This is an error message!')
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 stringlocalStorage.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! π