Today I saw a very interesting article, how to print colorful console.log? People on the front end are familiar with console.log, but so far I’ve been using it in its most common form, which is to print a message in the console. How can I apply a style to console.log? I don’t know if you know this?

console.log('%cHello'.'color: green; background: yellow: font-size: 30px');
Copy the code

As you can see, the above log statement consists of three parts: %c + message + style, where the identifier is followed by the message, the second parameter is the style, and the final output message is as defined by the style.

advantages

When dealing with a large application with a large number of log outputs, if you print a style log in some important places, you can quickly find it in the console instead of drowning in a pile of logs.

Chestnut 2

console.log(
  'Nothing here %cHi Cat %cHey Bear',  // Console Message
  'color: blue'.'color: red' // CSS Style
);
Copy the code

The effect is shown below. The text before the identifier is not affected.

Styles can be added to all five types of Console message

  • console.log
  • console.info
  • console.debug
  • console.warn
  • console.error
console.log('%cconsole.log'.'color: green; ');
console.info('%cconsole.info'.'color: green; ');
console.debug('%cconsole.debug'.'color: green; ');
console.warn('%cconsole.warn'.'color: green; ');
console.error('%cconsole.error'.'color: green; ');
Copy the code

Elegant delivery style practices

// 1. Const styles = ['color: green'.'background: yellow'.'font-size: 30px'.'border: 1px solid red'.'text-shadow: 2px 2px black'.'padding: 10px',
].join('; '); // 2. Join the items with semicolons to form a string // 3. Pass the styles variable console.log('%cHello There', styles);
Copy the code

You can even extract the message you want to output and save it in a variable

const styles = ['color: green'.'background: yellow'].join('; ');
const message = 'Some Important Message Here'; // 3. Pass the styles and message variables console.log('%c%s', styles, message);
Copy the code

Refer to the article medium.com/@samanthami…

Like the support of the like oh!