Colors in JavaScript console

前端 未结 27 2492
说谎
说谎 2020-11-22 11:42

Can Chrome\'s built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log\'s in green. Is that possible?

27条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 12:27

    I wrote a npm module that gives one the possibility to pass:

    • Custom colors - to both text and background;
    • Prefixes - to help identify the source, like [MyFunction]
    • Types - like warning, success, info and other predefined message types

    https://www.npmjs.com/package/console-log-plus

    Output (with custom prefixes):

    clp({
      type: 'ok',
      prefix: 'Okay',
      message: 'you bet'
    });
    clp({
      type: 'error',
      prefix: 'Ouch',
      message: 'you bet'
    });
    clp({
      type: 'warning',
      prefix: 'I told you',
      message: 'you bet'
    });
    clp({
      type: 'attention',
      prefix: 'Watch it!',
      message: 'you bet'
    });
    clp({
      type: 'success',
      prefix: 'Awesome!',
      message: 'you bet'
    });
    clp({
      type: 'info',
      prefix: 'FYI',
      message: 'you bet'
    });
    clp({
      type: 'default',
      prefix: 'No fun',
      message: 'you bet'
    });
    

    Output (without custom prefixes):

    Input:

    clp({
      type: 'ok',
      message: 'you bet'
    });
    clp({
      type: 'error',
      message: 'you bet'
    });
    clp({
      type: 'warning',
      message: 'you bet'
    });
    clp({
      type: 'attention',
      message: 'you bet'
    });
    clp({
      type: 'success',
      message: 'you bet'
    });
    clp({
      type: 'info',
      message: 'you bet'
    });
    clp({
      type: 'default',
      message: 'you bet'
    });
    

    To make sure the user won't render an invalid color, I wrote a color validator as well. It will validate colors by name, hex, rgb, rgba, hsl or hsla values

提交回复
热议问题