终端样式工具
有心者有所累、无心者无所谓
node
中chalk
工具、美化日志输出
1. 初始化一个包管理工具
$ npm init -y
$ npm init --yes
2. 安装chalk
包
$ npm install chalk
# 使用yarn也可以
$ yarn add chalk
3. 根目录创建index.js文件、内容如下
import chalk from chalk;
// 当前安装版本为5.2.0
cosnt log = console.log;
log(chalk.red('hello red!!!'));
提示错误如下
修改为require方式导入、提示如下错误:
官网提示5.x使用了esm、所以我们直接安装4.x就可以
重新安装chalk4.x版本
$ npm uninstall chalk
$ npm install chalk@4.x
重新执行则正常
4. chalk
api使用
4.1 基础样式使用
chalk
有四个等级0、1、2、3
- 0: 禁止使用颜色
- 1: 可以使用16种基础颜色
- 2: 可以使用256种颜色
- 3: 1600万种颜色支持
import {Chalk} from 'chalk';
const customChalk = new Chalk({level: 0});
4.2 基本颜色
import chalk from 'chalk';
const log = console.log
log(chalk.black('hello woeld!!!'));
log(chalk.red('hello woeld!!!'));
log(chalk.green('hello woeld!!!'));
log(chalk.yellow('hello woeld!!!'));
log(chalk.magenta('hello woeld!!!'));
log(chalk.cyan('hello woeld!!!'));
log(chalk.white('hello woeld!!!'));
log(chalk.blackBright('hello woeld!!!'));
log(chalk.redBright('hello woeld!!!'));
log(chalk.greenBright('hello woeld!!!'));
log(chalk.yellowBright('hello woeld!!!'));
log(chalk.blueBright('hello woeld!!!'));
log(chalk.magentaBright('hello woeld!!!'));
log(chalk.cyanBright('hello woeld!!!'));
log(chalk.whiteBright('hello woeld!!!'));
4.3 背景颜色
16种基础色修改为小驼峰增加前缀bg即可;
import chalk from 'chalk';
const log = console.log;
log(chalk.bgBlack('hello world!!!'));
log(chalk.bgRed('hello world!!!'));
log(chalk.bgGreen('hello world!!!'));
log(chalk.bgYellow('hello world!!!'));
log(chalk.bgBlue('hello world!!!'));
log(chalk.bgMagenta('hello world!!!'));
log(chalk.bgCyan('hello world!!!'));
log(chalk.bgWhite('hello world!!!'));
log(chalk.bgBlackBright('hello world!!!'));
log(chalk.bgRedBright('hello world!!!'));
log(chalk.bgGreenBright('hello world!!!'));
log(chalk.bgYellowBright('hello world!!!'));
log(chalk.bgBlueBright('hello world!!!'));
log(chalk.bgMagentaBright('hello world!!!'));
log(chalk.bgCyanBright('hello world!!!'));
log(chalk.bgWhiteBright('hello world!!!'));
4.4 修饰符
chalk语法支持链式调用
import chalk from 'chalk';
const log = console.log;
log(chalk.red.reset('hello world !!!'));
log(chalk.red.bold.underline('Hello', 'world'));
log(chalk.red.dim('hello', 'world'));
log(chalk.red.italic('hello', 'world'));
log(chalk.red.inverse('hello', 'world'));
log(chalk.red.hidden('hello', 'world'));
log(chalk.red.strikethrough('hello', 'world'));
log(chalk.red.visible('hello', 'world'));
结果如下
4.5 256和真彩色
import chalk from 'chalk';
const log = console.log;
chalk.rgb(255, 136, 0).bold('Orange!')
chalk.hex('#FF8800').bold('Orange!')
chalk.bgAnsi256(194)('Honeydew, more or less')
结果如下
5.浏览器支持情况
- chrome69+
- 如果是windows、请使用git bash 而不是cmd