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

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


当前回答

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

npm i chalk

其他回答

旧版本的Chrome不允许你让console.log()以编程方式显示特定的颜色,但是调用console.error()会在错误行上放一个红色的X图标,并使文本变成红色,而console.warn()会让你变成黄色!图标。

然后,您可以使用控制台下面的All、Errors、Warnings和Logs按钮筛选控制台条目。


Firebug支持控制台的自定义CSS。从2010年开始,Chrome支持已经添加到Chrome 24。

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55',
            'more text');

当%c出现在第一个参数中的任何位置时,下一个参数将用作设置控制台行样式的CSS。进一步的参数被连接起来(一如既往)。

模板系统,有用的,如果你想创建彩色的行文本,而不为每个块创建完整的风格

var tpl = 'background-color:greenyellow; border:3px solid orange; font-size:18px; font-weight: bold;padding:3px 5px;color:';
console.log('%cMagenta %cRed %cBlue', `${tpl} magenta`, `${tpl} Red`,`${tpl} #4274fb`);

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

//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')

看看这个:

控制台动画,加上CSS

(function() {
  var frame = 0;
  var frames = [
    "This",
    "is",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!",
    " ",
    "SPARTA!"
  ];
  var showNext = () => {
    console.clear();
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    console.log(
      `%c ${frames[frame]}`,
      "background: red; color: white; font-size: 25px; padding: 3px 40%;"
    );
    console.log(
      `%c `,
      "background: red; color: white; font-size: 15px; padding: 3px 41%;"
    );
    setTimeout(
      showNext,
      frames[frame] === "SPARTA!" || frames[frame] === " " ? 100 : 1500
    );
    // next frame and loop
    frame++;
    if (frame >= frames.length) {
      frame = 0;
    }
  };
  showNext();
})();

https://jsfiddle.net/a8y3jhfL/

你可以在每一帧中粘贴ASCII来观看ASCII动画

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

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`);