給 console 添加顏色

簡(jiǎn)評(píng):使用 %c 聲明可以給 console 的輸出添加 CSS 樣式,日志太多的話,給不同種類的日志設(shè)置不同的樣式,可以極大的提升閱讀體驗(yàn)。

什么是 %c

%c: 標(biāo)識(shí)將 CSS 樣式應(yīng)用于 %c 之后的 console 消息。

給 console 消息設(shè)置多個(gè)樣式

可以給同一條 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 樣式

如果要輸出的樣式比較多,字符串會(huì)比較長(zhǎng),這里有一個(gè)小技巧, 生成一個(gè) CSS Array ,通過 join(';') 來合并成一個(gè) 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.連接單個(gè)數(shù)組項(xiàng)并將它們連接成一個(gè)用分號(hào)分隔的字符串(;)
// 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
推薦閱讀:空行會(huì)影響 Java 編譯嗎?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容