简评:使用 %c 声明能够给 console 的输出添加 CSS 样式,日志太多的话,给不一样种类的日志设置不一样的样式,能够极大的提高阅读体验。
%c: 标识将 CSS 样式应用于 %c 以后的 console 消息。css
能够给同一条 Console 消息设置多种颜色。node
console.log( 'Nothing here %cHi Cat %cHey Bear', // Console Message 'color: blue', 'color: red' // CSS Style );
这里有五种 console 类型的消息:数组
console.log
console.info
console.debug
console.warn
console.error
你能够自定义本身的日志样式,例如:spa
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;');
若是要输出的样式比较多,字符串会比较长,这里有一个小技巧, 生成一个 CSS Array ,经过 join(';') 来合并成一个 CSS String。debug
例如:日志
// 1.将css样式传递给数组 const styles = [ 'color:green', 'background:yellow', 'font-size:30px', 'border:1px solid red', 'text-shadow:2px 2px black', 'padding:10px', ]。join(';'); // 2.链接单个数组项并将它们链接成一个用分号分隔的字符串(;) // 3.传递样式变量 console.log('%cHello There',styles); // or console.log('%c%s', styles, 'Some Important Message Here');
在 node.js 环境,你能够使用 Color Reference 来设置样式。例如:code
// Cyan console.log('\x1b[36m%s\x1b[0m', 'I am cyan'); // Yellow console.log('\x1b[33m%s\x1b[0m', 'yellow' );
原文: Colorful Console Message