ctext
v0.1.0
Published
Lightweight terminal color text utility with chainable API and multi-style support. Zero dependencies, pure ANSI escape codes implementation.
Maintainers
Readme
ctext
轻量级的终端彩色文本工具,支持链式调用和多样式组合。
特性
- 🎯 推荐用法:直接传入多样式,简洁易读
- 🎨 丰富的颜色和样式选项
- 🔗 灵活的链式调用
- 📦 零依赖,纯 ANSI 转义码实现
- 💡 完整的 TypeScript 类型支持
安装
pnpm add ctext使用方法
推荐:直接传入多样式
这是最简洁、可读性最好的方式,避免过长的链式调用:
import { ctext } from 'ctext';
// 单个文本多样式
console.log(ctext('成功', 'green', 'bold'));
console.log(ctext('http://www.tt.com', 'blue', 'underline'));
// 多个文本组合
console.log(
ctext('访问: ', 'cyan')
.ctext('https://example.com', 'blue', 'underline')
);
// 复杂样式组合
console.log(
ctext(' ERROR ', 'white', 'bold', 'bgRed')
.ctext(' ')
.ctext('发生错误', 'red', 'bold')
);链式样式定义
样式可以先定义,文本后传入(样式会累积到下一个有文本的调用):
// 样式归下一个有文本的
console.log(ctext().blue().underline('http://www.tt.com').ctext().red('地址'));
// 等价于
console.log(ctext('http://www.tt.com', 'blue', 'underline').ctext('地址', 'red'));混合使用
根据场景灵活选择:
console.log(
ctext('[ERROR]', 'red', 'bold')
.ctext(' ')
.ctext('警告信息: ', 'yellow')
.ctext()
.white()
.underline('详细内容')
);API
颜色
前景色:
black(),red(),green(),yellow(),blue(),magenta(),cyan(),white(),gray()brightRed(),brightGreen(),brightYellow(),brightBlue(),brightMagenta(),brightCyan(),brightWhite()
背景色:
bgBlack(),bgRed(),bgGreen(),bgYellow(),bgBlue(),bgMagenta(),bgCyan(),bgWhite()bgBrightRed(),bgBrightGreen(),bgBrightYellow(),bgBrightBlue(),bgBrightMagenta(),bgBrightCyan(),bgBrightWhite()
样式
bold()- 粗体dim()- 暗淡italic()- 斜体underline()- 下划线inverse()- 反色hidden()- 隐藏strikethrough()- 删除线
方法签名
每个样式方法都支持可选的文本参数:
.red() // 仅添加样式,等待文本
.red('文本') // 添加样式并立即应用到文本ctext() 方法
用于继续链式调用或应用多个样式:
ctext(text?: string, ...styles: StyleType[]): CText更多示例
日志级别
// 推荐写法:直接传入多样式
console.log(ctext(' INFO ', 'white', 'bold', 'bgBlue').ctext(' 这是一条信息', 'cyan'));
console.log(ctext(' WARN ', 'black', 'bold', 'bgYellow').ctext(' 这是一条警告', 'yellow'));
console.log(ctext(' ERROR ', 'white', 'bold', 'bgRed').ctext(' 这是一条错误', 'red'));链接和文本
console.log(ctext('访问: ', 'cyan').ctext('https://example.com', 'blue', 'underline'));
console.log(ctext('文档: ', 'gray').ctext('README.md', 'brightBlue', 'underline'));成功/失败状态
console.log(ctext('✓', 'green', 'bold').ctext(' 测试通过'));
console.log(ctext('✗', 'red', 'bold').ctext(' 测试失败'));
console.log(ctext('⚠', 'yellow', 'bold').ctext(' 警告信息'));表格和列表
// 表格标题
console.log(ctext(' 名称 ', 'white', 'bold', 'bgBlue').ctext(' | ').ctext(' 状态 ', 'white', 'bold', 'bgBlue'));
// 列表项
console.log(ctext('1.', 'cyan', 'bold').ctext(' 第一项', 'white'));
console.log(ctext('2.', 'cyan', 'bold').ctext(' 第二项', 'white'));高亮和强调
console.log(ctext('重要', 'red', 'bold', 'underline').ctext(' 这是重要信息'));
console.log(ctext('已废弃', 'gray', 'strikethrough').ctext(' → ').ctext('使用新方法', 'green', 'italic'));License
MIT
