Did you face a situation where you wanted to show console messages with different colors ?
Yeah it can be done easily in the browser!
example,On Chrome & Firefox you can add CSS in console.log messages
like this
console.log('%c%s','background: #c7c7c7; color: #fdfd10; font-size: 24px;' , 'This could be you warning message with Gray background');
console.log('%c%s','background: #222; color: #13ff1c; font-size: 24px;' , 'This could be you Success Message with black background');
You can wrap it as a function that takes the console message type and apply styling before logging that :-
const logMessage =(message, mType) =>{
let color = "black";
let bgColor = "white";
let fontSize = "12px";
switch (mType) {
case "warning":
color = "yellow";
bgColor = "Gray";
fontSize ="30px";
break;
case "info":
color = "gray";
bgColor = "cyan";
fontSize ="30px";
break;
case "error":
color = "red";
bgColor = "blue";
fontSize ="30px";
break;
case "success":
color = "green";
bgColor = "pink";
fontSize ="30px";
break;
}
console.log(`%c${message}`, `color:${color}; background-color:${bgColor}; font-size:${fontSize};`)
}
logMessage('Test Warning Message:', 'warning')
logMessage('Test Info Message:', 'info')
logMessage('Test Error Message:', 'error')
logMessage('Test Message Success:', 'success')
Another nice way to console complex data is to use the console.table:-
Lets say that you have an object and you wanna check it in the console in an understandable nice way then the console table is the answer
const employee ={name:"Ahmed",age:"36",country:"Jordan"};
console.table(employee);
OK ok... thats cool and nice but what about the terminal ?
Will Meet CHALK ,
https://www.npmjs.com/package/chalk
A very nice npm package that allow you to style the console messages
it support nested styling.
really easy to use: just import the package and call chalk.neededColor
inside your console.log() statement
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
Its Also allow you to define your own them , just like what did we do with our previous logMessage function
const chalk = require('chalk');
//define message type and reuse them whenever you want
const warning = chalk.bold.yellow;
const info = chalk.bold.blue;
const error = chalk.bold.red;
const success = chalk.bold.green;
console.log(warning('Warning!'));
console.log(info('Info!'));
console.log(error('Error!'));
console.log(success('Success!'));
here is an example of last message of my terminal today
I hope You Like it
Top comments (0)