chalk

17 2月

chalk命令行工具,具有轻量级,高性能,学习成本低等特点,适合优化命令行交互。

API非常简单,支持链式调用:chalk.<style>[.<style>…](string, [string…])。参数是个字符串数组。调用链顺序无所谓,但为了避免冲突,放在最后的优先级最高,所以chalk.red.yellow.green等价于chalk.green

const chalk = require('chalk');
const log = console.log;

log(chalk.blue('Hello') + ' World' + chalk.red('!'));            // 设颜色
log(chalk.blue.bgRed.bold('Hello world!'));                      // 也可以设背景色,加粗
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));  // 参数支持字符串数组

log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));  // 支持嵌套使用,下划线

// ES6写法
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// ES6写法
log(chalk`
CPU: {red 90%}
RAM: {green 40%}
DISK: {rgb(255,131,0) 70%}
`);

log(chalk.keyword('orange')('Yay for orange colored text!'));       // 指定颜色名
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));  // 自定义颜色
log(chalk.hex('#DEADED').bold('Bold gray!'));                       // 自定义颜色

也可以自定义你的主题:

const chalk = require('chalk');

const error = chalk.bold.red;
const warning = chalk.keyword('orange');

console.log(error('Error!'));
console.log(warning('Warning!'));

支持的颜色 Colors:

black
red
green
yellow
blue
magenta
cyan
white
gray
redBright
greenBright
yellowBright
blueBright
magentaBright
cyanBright
whiteBright

支持的背景色 Background colors:

bgBlack
bgRed
bgGreen
bgYellow
bgBlue
bgMagenta
bgCyan
bgWhite
bgBlackBright
bgRedBright
bgGreenBright
bgYellowBright
bgBlueBright
bgMagentaBright
bgCyanBright
bgWhiteBright

支持的字体方法:

reset - Resets the current color chain.
bold - Make text bold.
dim - Emitting only a small amount of light.
italic - Make text italic. (Not widely supported)
underline - Make text underline. (Not widely supported)
inverse- Inverse background and foreground colors.
hidden - Prints the text, but makes it invisible.
strikethrough - Puts a horizontal line through the center of the text. (Not widely supported)
visible- Prints the text only when Chalk is enabled. Can be useful for things that are purely cosmetic.

可以用chalk.enabled关闭粉笔:

const ctx = new chalk.constructor({enabled: false});

可以用chalk.level设置粉笔的属性:

const ctx = new chalk.constructor({level: 0});
// level 值如下:
// 0:All colors disabled
// 1:Basic color support (16 colors)
// 2:256 color support
// 3:Truecolor support (16 million colors)

发表评论

电子邮件地址不会被公开。 必填项已用*标注