给 console 添加颜色

简评:使用 %c 声明可以给 console 的输出添加 CSS 样式,日志太多的话,给不同种类的日志设置不同的样式,可以极大的提升阅读体验。

什么是 %c

%c: 标识将 CSS 样式应用于 %c 之后的 console 消息。

给 console 消息设置多个样式

可以给同一条 Console 消息设置多种颜色。

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

给其他 console 消息设置样式

这里有五种 console 类型的消息:

  • 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;'); 

处理多种 CSS 样式

如果要输出的样式比较多,字符串会比较长,这里有一个小技巧, 生成一个 CSS Array ,通过 join(’;’) 来合并成一个 CSS String。

例如:

// 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 中设置 console 消息样式

在 node.js 环境,你可以使用 Color Reference 来设置样式。例如:

// Cyan
console.log('\x1b[36m%s\x1b[0m', 'I am cyan');
// Yellow
console.log('\x1b[33m%s\x1b[0m', 'yellow' );

原文:  Colorful Console Message

猜你喜欢

转载自blog.csdn.net/jpush/article/details/84576835
今日推荐