命令行终端-美化-picocolors

621 阅读1分钟

我们在开发项目或者开发node cli 工具,希望我们的终端输出友好的日志提示,带有颜色,背景等等

今天推荐一个美化终端输出的js 库 picocolors


github 地址-picocolors

vite也在用哟~

特点

  • 无依赖
  • chalk 库 小14倍, 快 2倍
  • PostCSS、SVGO、Stylelint 和 Browserslist 等流行工具都在使用
  • 支持 node 6+ 和浏览器, 支持 CJS 和ESM 项目
  • 自带TypeScript 类型声明。
  • NO_COLOR 友好。

安装

npm i picocolors

pnpm add picocolors

快速上手

import pc from "picocolors"

console.log(
  pc.green(`How are ${pc.italic(`you`)} doing?`)
)

image.png

Picocolors 提供了一个对象,其中包括各种文本着色和格式设置功能

文字颜色

  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white
  • gray
console.log(`I see a ${pc.red("red door")} and I want it painted ${pc.black("black")}`)

背景颜色

  • bgBlack
  • bgRed
  • bgGreen
  • bgYellow
  • bgBlue
  • bgMagenta
  • bgCyan
  • bgWhite
console.log(
  pc.bgBlack(
    pc.white(`Tom appeared on the sidewalk with a bucket of whitewash and a long-handled brush.`)
  )
)

其他

除了设置背景颜色和文字颜色,还可以设置其他效果

dimboldhiddenitalicunderlinestrikethroughresetinverse

import pc from "picocolors"

console.log(
  pc.green(`How are ${pc.italic(`you`)} doing?`)
)

console.log(`I see a ${pc.red("red door")} and I want it painted ${pc.black("black")}`)

console.log(
  pc.bgRed(
    pc.white(`Tom appeared on the sidewalk with a bucket of whitewash and a long-handled brush.`)
  )
)

console.log(pc.bold('加粗'), '普通文字');

image.png

实用的工具函数

  • isColorSupported 返回 boolean , 当前环境,是否支持使用 颜色编码和格式
import pc from "picocolors"

if (pc.isColorSupported) {
  console.log("Yay! This script can use colors and formatters")
}
  • createColors(enabled) 返回具有手动定义颜色支持配置的新 API 对象的函数
import pc from "picocolors"

let { red, bgWhite } = pc.createColors(options.enableColors)

使用 picocolors 替代 chalk

  1. 第一步, 替换导入的包
- import chalk from 'chalk'
+ import pico from 'picocolors'
  1. 第二步,替换使用
- chalk.red(text)
+ pico.red(text)
  1. 如果存在链式调用,则替换为 嵌套的写法
- chalk.red.bold(text)
+ pico.red(pico.bold(text))
  1. 可以使用 colorize-template 来替换 chalk 的标记模板文字

这个一般使用的比较少

+ import { createColorize } from 'colorize-template'

+ let colorize = createColorize(pico)
- chalk.red.bold`full {yellow ${"text"}}`
+ colorize`{red.bold full {yellow ${"text"}}}`

另外, chalk 地址: 传送门