Colorful console log on browser

0
2896
Colorful Console Log
Colorful Console Log

This is a pretty nice trick to print out colorful text on browser console.

To achieve this, use the following piece of code, taken from this gist


function logColor(color, args) {
    console.log(`%c ${args.join(' ')}`, `color: ${color}`);
}

const log = {
  aliceblue: (...args) => { logColor('aliceblue', args)},
  antiquewhite: (...args) => { logColor('antiquewhite', args)},
  aqua: (...args) => { logColor('aqua', args)},
  aquamarine: (...args) => { logColor('aquamarine', args)},
  azure: (...args) => { logColor('azure', args)},
  ...
}

So you can just pick a color as a method for logging:


log.aqua('this is aqua');
log.chocolate('i <3 chocolate');

However, that’s kinda manual to add all color entries. To improve this, we can just make use of modern ES6 by proxifying the console.log property.


const log = new Proxy({}, {
  get: (_, colour) => function() {
    console.log(`%c ${[].slice.call(arguments).join(' ')}`, `color: ${colour}`)
  }
})

// example
log.tomato('I am tomato')
log.chocolate('I am chocolate')

It’s taken from this brilliant gist.