Chrome内置的JavaScript控制台可以显示颜色吗?

我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?


当前回答

我为它创建了一个包。cslog

使用

npm i cslog

像这样使用它

import log from 'cslog'

log.h2("This is heading 2")
log.p("This is colored paragraph")
log.d(person, "Person Info")

你也可以自定义颜色。在这里

其他回答

在Chrome & Firefox(+31)中,您可以在console.log消息中添加CSS:

console.log('%c我的天哪!', '背景:#222;颜色:# bada55 ');

同样适用于在同一命令中添加多个CSS。

参考文献

MDN:样式化控制台输出 Chrome:控制台API参考

如果你想给你的终端控制台上色,那么你可以使用npm包粉笔

npm i chalk

您可以使用自定义样式表为调试器着色。你可以把这段代码放在C:\Documents and Settings<用户名>\Local Settings\Application Data\谷歌\Chrome\用户数据\Default\用户样式表\Custom.css(如果你在WinXP中),但是目录因操作系统不同而不同。

.console-error-level .console-message-text{
    color: red;
}

.console-warning-level .console-message-text {
    color: orange;
}

.console-log-level .console-message-text {
    color:green;
}

几年前,我为自己写了一个非常非常简单的插件:

要添加到你的页面,你所需要做的就是把这个放在头部:

<script src="https://jackcrane.github.io/static/cdn/jconsole.js" type="text/javascript">

然后在JS中:

jconsole.color.red.log('hellllooo world');

该框架有以下代码:

jconsole.color.red.log();
jconsole.color.orange.log();
jconsole.color.yellow.log();
jconsole.color.green.log();
jconsole.color.blue.log();
jconsole.color.purple.log();
jconsole.color.teal.log();

以及:

jconsole.css.log("hello world","color:red;");

对于任何其他css。上面的代码是用以下语法设计的:

jconsole.css.log(message to log,css code to style the logged message)

选项1

// log-css.js v2
const log = console.log.bind()
const css = (text, options) => {
    let cssOptions = ''
    for (let prop in options) {
        const value = options[prop]
        prop = camelCaseToDashCase(prop)
        cssOptions += `${prop}: ${value}; `
    }
    return [`%c${text}`, cssOptions.trim()]

    function camelCaseToDashCase(value) {
        return value.replace(/[A-Z]/g, matched => `-${matched.toLowerCase()}`)
    }
}

例子:

log(...css('Example =P', {
    backgroundColor: 'blue',
    color: 'white',
    // fontFamily: 'Consolas',
    fontSize: '25px',
    fontWeight: '700',
    // lineHeight: '25px',
    padding: '7px 7px'
}))

选项2

我现在创建log-css.js https://codepen.io/luis7lobo9b/pen/QWyobwY

// log-css.js v1
const log = console.log.bind();
const css = function(item, color = '#fff', background = 'none', fontSize = '12px', fontWeight = 700, fontFamily) {
    return ['%c ' + item + ' ', 'color:' + color + ';background:' + background + ';font-size:' + fontSize + ';font-weight:' + fontWeight + (fontFamily ? ';font-family:' + fontFamily : '')];
};

例子:

log(...css('Lorem ipsum dolor sit amet, consectetur adipisicing elit.', 'rebeccapurple', '#000', '14px'));