极简版colorful console.log

// raw.
console.log('hello,world!')
console.info('hello,world!')
console.warn('hello,world!')
console.error('hello,world!')

const console = new Proxy(globalThis.console, {
  get(target, prop) {
    switch(prop) {
      case 'log':
      case 'info':
      case 'warn':
      case 'error':
        // console.log(receiver)
        const rawfunc = target[prop];
        return (function embeddedRawfunc() {
          const color = {
            // ANSI Color Codes --- Basic Color
            // https://talyian.github.io/ansicolors/
            // foreground
            'black': '\x1b[30m%s\x1b[0m',
            'red': '\x1b[31m%s\x1b[0m',
            'green': '\x1b[32m%s\x1b[0m',
            'yellow': '\x1b[33m%s\x1b[0m',
            'blue': '\x1b[34m%s\x1b[0m',
            'magenta': '\x1b[35m%s\x1b[0m',
            'cyan': '\x1b[36m%s\x1b[0m',
            'white': '\x1b[37m%s\x1b[0m',
            // background
            // 97=WhiteBright
            'bgblack': '\x1b[97m\x1b[40m%s\x1b[0m',
            'bgred': '\x1b[97m\x1b[41m%s\x1b[0m',
            'bggreen': '\x1b[97m\x1b[42m%s\x1b[0m',
            'bgyellow': '\x1b[97m\x1b[43m%s\x1b[0m',
            'bgblue': '\x1b[97m\x1b[44m%s\x1b[0m',
            'bgmagenta': '\x1b[97m\x1b[45m%s\x1b[0m',
            'bgcyan': '\x1b[97m\x1b[46m%s\x1b[0m',
            'bgwhite': '\x1b[97m\x1b[47m%s\x1b[0m',
          }
          for (const key in color) {
            rawfunc[key] = (...args) => rawfunc(color[key], args)
          }
          return rawfunc;
        })()
      default:
        return target[prop]   
    }
  }  
})
// e.g.
console.log.black('hello,world!')
console.log.red('hello,world!')
console.log.green('hello,world!')
console.log.yellow('hello,world!')
console.log.blue('hello,world!')
console.log.magenta('hello,world!')
console.log.cyan('hello,world!')
console.log.white('hello,world!')
console.log.bgblack('hello,world!')
console.log.bgred('hello,world!')
console.log.bggreen('hello,world!')
console.log.bgyellow('hello,world!')
console.log.bgblue('hello,world!')
console.log.bgmagenta('hello,world!')
console.log.bgcyan('hello,world!')
console.log.bgwhite('hello,world!')
posted @ 2023-07-17 14:26  汪淼焱  阅读(34)  评论(0编辑  收藏  举报