簡評:使用 %c 聲明可以給 console 的輸出添加 CSS 樣式删豺,日志太多的話,給不同種類的日志設(shè)置不同的樣式甫贯,可以極大的提升閱讀體驗(yàn)吼鳞。
什么是 %c
%c: 標(biāo)識將 CSS 樣式應(yīng)用于 %c 之后的 console 消息。
給 console 消息設(shè)置多個樣式
可以給同一條 Console 消息設(shè)置多種顏色叫搁。
console.log(
'Nothing here %cHi Cat %cHey Bear', // Console Message
'color: blue', 'color: red' // CSS Style
);
給其他 console 消息設(shè)置樣式
這里有五種 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樣式傳遞給數(shù)組
const styles = [
'color:green'雪位,
'background:yellow',
'font-size:30px'梨撞,
'border:1px solid red'雹洗,
'text-shadow:2px 2px black',
'padding:10px'卧波,
]时肿。join(';'); // 2.連接單個數(shù)組項(xiàng)并將它們連接成一個用分號分隔的字符串(;)
// 3.傳遞樣式變量
console.log('%cHello There',styles);
// or
console.log('%c%s', styles, 'Some Important Message Here');
在 Node.js 中設(shè)置 console 消息樣式
在 node.js 環(huán)境港粱,你可以使用 Color Reference 來設(shè)置樣式螃成。例如:
// Cyan
console.log('\x1b[36m%s\x1b[0m', 'I am cyan');
// Yellow
console.log('\x1b[33m%s\x1b[0m', 'yellow' );
原文鏈接:Colorful Console Message
推薦閱讀:空行會影響 Java 編譯嗎旦签?