使用多个参数时如何将颜色应用于 console.log?

How to apply colors to console.log when using multiple arguments?

我正在尝试设置我的 console.log() 输出的样式以突出我的应用程序错误。

到目前为止这有效:

console.log('%cHello World', 'background: #222; color: #bada55');

但事实并非如此:

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log('%c', text, style);

只是 returns background: #222; color: #bada55。我错过了什么?

您使用模板文字

%c 之后的第一个参数中添加 text

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log(`%c${text}`, style);

如果没有模板字符串,它将是

var text = "Hello World";
var style = "background: #222; color: #bada55";
console.log('%c' + text, style);

当您需要记录多个参数时,可以使用以下方法:

const log = (...args) => {
  let messageConfig = '%c%s   ';

  args.forEach((argument) => {
    const type = typeof argument;
    switch (type) {
        case 'bigint':
        case 'number':
        case 'boolean':
            messageConfig += '%d   ';
            break;

        case 'string':
            messageConfig += '%s   ';
            break;

        case 'object':
        case 'undefined':
        default:
            messageConfig += '%o   ';
    }
  });

  console.log(messageConfig, 'color: orange', '[LOGGER]', ...args);
};

log('my message', 123, 'qwerty', { foo: 'bar' }, [1, 2, 3, 4, 5]);

结果如下: