給 console 新增顏色
阿新 • • 發佈:2018-12-05
簡評:使用 %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' );