更好的 console.logs
如果您经常使用 javascript,那么您可能经常需要使用console.log()
它来输出一些信息。
但这通常只是一种简单的老方法:
(() => {
// do stuff
console.log('Success!')
})()
这里有几种方法可以使你的日志更具视觉信息量,也更有趣 🙂
用于console.error()
错误日志
(() => {
// do stuff
console.error('Oops, something went wrong!')
})()
用于console.warn()
警告日志
(() => {
// do stuff
console.warn('Warning! Something doesnt seem right.')
})()
[编辑]console.table()
用于可迭代对象
function Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
const me = new Person('John', 'Smith')
console.table(me)
添加您的自定义样式
(() => {
// do stuff
console.log('%c%s',
'color: green; background: yellow; font-size: 24px;','Success!')
})()
您可以在代码中使用自定义函数,以便直接使用带有颜色的“您自己的”日志
function customLog(message, color='black') {
switch (color) {
case 'success':
color = 'Green'
break
case 'info':
color = 'Blue'
break;
case 'error':
color = 'Red'
break;
case 'warning':
color = 'Orange'
break;
default:
color = color
}
console.log(`%c${message}`, `color:${color}`)
}
customLog('Hello World!')
customLog('Success!', 'success')
customLog('Error!', 'error')
customLog('Warning!', 'warning')
customLog('Info...', 'info')
这是笔。
希望您觉得这篇文章有用,并祝您调试愉快!😊
文章来源:https://dev.to/wangonya/better-consolelogs-448c