基础项目搭建
用 Chalk 美化终端输出
为 CLI 输出添加颜色与样式
Chalk 简介
在已有「commander + prompts」的 CLI 上,使用 chalk 可以为 console.log 等输出加上颜色、加粗、下划线等样式,让成功/错误/提示信息更易区分,提升可读性。
特点概览:
- 颜色丰富 — 前景色、背景色多种可选,如
chalk.blue、chalk.bgRed - 链式 API — 可组合多种样式,如
chalk.blue.bold('text') - 跨平台 — 会检测终端是否支持颜色,不支持时自动降级
- ESM / TypeScript — chalk 5+ 为纯 ESM,并带类型定义
常用写法:
chalk.blue(text)— 蓝色文字chalk.red.bold(text)— 红色加粗chalk.green.bgBlack(text)— 绿字黑底chalk.cyan.underline(text)— 青色下划线
初始化步骤
1. 安装 chalk
在项目根目录安装。官方仓库: chalk
npm install chalk -w @repo/cg2. 导入 chalk 模块
在 src/cmd/root.ts 顶部增加 chalk 的默认导入,与 commander、prompts 的导入放在一起即可。
import { Command } from 'commander'
import { input } from '@inquirer/prompts'
import chalk from 'chalk'
// ... 其他代码3. 用 chalk 美化输出
把原来直接打印的「你的名字是:」后面的内容,改为通过 chalk.blue(answer) 输出,这样用户输入的名字会以蓝色显示,便于和普通日志区分。
program
.name('code-gen')
.description('代码生成器 CLI 工具')
.version('1.0.0')
.action(async () => {
console.log('代码生成cmd工具')
const answer = await input({ message: '输入你的名字' })
// console.log("你的名字是:", answer);
console.log('你的名字是:', chalk.blue(answer))
})说明: 这里仅用蓝色示例,你可按需换成 chalk.green、chalk.cyan 等;需要加粗或下划线时可链式调用,如 chalk.blue.bold(answer)。
4. 完整代码示例
import { Command } from 'commander'
import { input } from '@inquirer/prompts'
import chalk from 'chalk'
const program = new Command()
program
.name('code-gen')
.description('代码生成器 CLI 工具')
.version('1.0.0')
.action(async () => {
console.log('代码生成cmd工具')
const answer = await input({ message: '输入你的名字' })
console.log('你的名字是:', chalk.blue(answer))
})
program.parse()5. 运行测试
在项目根目录执行:
bun run packages/cg/src/index.ts预期效果: 与 prompts 步骤类似,区别是「你的名字是:」后面的名字会以蓝色显示(在支持颜色的终端中)。
6. 更多样式示例
// 单色
console.log(chalk.blue('蓝色'))
console.log(chalk.red('红色'))
console.log(chalk.green('绿色'))
// 链式:颜色 + 加粗/下划线
console.log(chalk.cyan.bold('青色加粗'))
console.log(chalk.yellow.underline('黄色下划线'))
// 模板字符串
console.log(chalk`{red 错误} {green 成功}`)Git 提交
git add .
git commit -m "feat: 使用 chalk 美化终端输出"