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

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


当前回答

选项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'));

其他回答

我怀疑是否有人会真正看到它,但对于那些想要在同一条线上混合几种颜色的人,我有一个简单的解决方案:

export enum Colors {
    Black = '\033[30m',
    Red = '\x1b[31m',
    Green = '\x1b[32m',
    Yellow = '\x1b[33m',
    Blue = '\033[34m',
    Magenta = '\033[35m',
    Cyan = '\033[36m',
    White = '\033[37m'
}


function color(text: string, color: color: Colors) {
    return `${color}${text}\x1b[0m`;
}


console.log(`This is ${color('green text', Colors.Green)} but this is black. This is red ${color('red', Colors.Red)} etc`);

我最近想解决一个类似的问题,构造了一个小函数,只对我关心的关键字进行着色,这些关键字很容易通过周围的花括号{keyword}识别。

这招很管用:

var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
var splitText = text.split(' ');
var cssRules = [];
var styledText = '';
_.each(splitText, (split) => {
    if (/^\{/.test(split)) {
        cssRules.push('color:blue');
    } else {
        cssRules.push('color:inherit')
    }
    styledText += `%c${split} `
});
console.log(styledText , ...cssRules)

从技术上讲,您可以用switch/case语句替换if语句,以允许根据不同的原因使用多种样式

有一系列内置函数用于为控制台日志上色:

//For pink background and red text
console.error("Hello World");  

//For yellow background and brown text
console.warn("Hello World");  

//For just a INFO symbol at the beginning of the text
console.info("Hello World");  

//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code

//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')

选项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'));

我写了template-colors-web https://github.com/icodeforlove/Console.js,让我们更容易做到这一点

console.log(c`red ${c`green ${'blue'.bold}.blue`}.green`.red);

使用默认的console.log将很难做到以上这些。

现场互动演示点击这里。