Skip to main content

Chalk 中文网

正确完成终端字符串样式

¥Terminal string styling done right

信息

¥Info

亮点

¥Highlights

安装

¥Install

npm install chalk

重要:Chalk 5 是 ESM。如果你想将 Chalk 与 TypeScript 或构建工具一起使用,你可能希望暂时使用 Chalk 4。阅读更多。

¥IMPORTANT: Chalk 5 is ESM. If you want to use Chalk with TypeScript or a build tool, you will probably want to use Chalk 4 for now. Read more.

用法

¥Usage

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));

Chalk 带有易于使用的可组合 API,你只需链接和嵌套所需的样式即可。

¥Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

import chalk from 'chalk';

const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));

// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// Use RGB colors in terminal emulators that support it.
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));

轻松定义你自己的主题:

¥Easily define your own themes:

import chalk from 'chalk';

const error = chalk.bold.red;
const warning = chalk.hex('#FFA500'); // Orange color

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

利用 console.log 字符串替换

¥Take advantage of console.log string substitution:

import chalk from 'chalk';

const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'

API

chalk.<style>[.<style>...](string, [string...])

示例:chalk.red.bold.underline('Hello', 'world');

¥Example: chalk.red.bold.underline('Hello', 'world');

链接 styles 并将最后一个作为带有字符串参数的方法调用。顺序无关紧要,如果发生冲突,后面的样式优先。这仅仅意味着 chalk.red.yellow.green 相当于 chalk.green

¥Chain styles and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that chalk.red.yellow.green is equivalent to chalk.green.

多个参数将以空格分隔。

¥Multiple arguments will be separated by space.

chalk.level

指定颜色支持级别。

¥Specifies the level of color support.

会自动检测颜色支持,但你可以通过设置 level 属性来覆盖它。但是,你只应在自己的代码中执行此操作,因为它全局适用于所有 Chalk 消费者。

¥Color support is automatically detected, but you can override it by setting the level property. You should however only do this in your own code as it applies globally to all Chalk consumers.

如果你需要在可重用模块中更改此设置,请创建一个新实例:

¥If you need to change this in a reusable module, create a new instance:

import {Chalk} from 'chalk';

const customChalk = new Chalk({level: 0});
级别描述
0禁用所有颜色
1基本颜色支持(16 种颜色)
2支持 256 种颜色
3真彩色支持(1600 万种颜色)

supportsColor

检测终端是否 支持颜色。内部使用并为你处理,但为了方便而公开。

¥Detect whether the terminal supports color. Used internally and handled for you, but exposed for convenience.

用户可以使用标志 --color--no-color 覆盖。对于无法使用 --color 的情况,请使用环境变量 FORCE_COLOR=1(级别 1)、FORCE_COLOR=2(级别 2)或 FORCE_COLOR=3(级别 3)强制启用颜色,或使用 FORCE_COLOR=0 强制禁用。使用 FORCE_COLOR 会覆盖所有其他颜色支持检查。

¥Can be overridden by the user with the flags --color and --no-color. For situations where using --color is not possible, use the environment variable FORCE_COLOR=1 (level 1), FORCE_COLOR=2 (level 2), or FORCE_COLOR=3 (level 3) to forcefully enable color, or FORCE_COLOR=0 to forcefully disable. The use of FORCE_COLOR overrides all other color support checks.

可以分别使用 --color=256--color=16m 标志启用显式 256/真彩色模式。

¥Explicit 256/Truecolor mode can be enabled using the --color=256 and --color=16m flags, respectively.

chalkStderr 和 supportsColorStderr

¥chalkStderr and supportsColorStderr

chalkStderr 包含一个单独的实例,该实例配置了针对 stderr 流而不是 stdout 检测到的颜色支持。supportsColor 中的覆盖规则也适用于此。supportsColorStderr 为方便起见而公开。

¥chalkStderr contains a separate instance configured with color support detected for stderr stream instead of stdout. Override rules from supportsColor apply to this too. supportsColorStderr is exposed for convenience.

修饰符名称、前景颜色名称、背景颜色名称和颜色名称

¥modifierNames, foregroundColorNames, backgroundColorNames, and colorNames

为方便起见,所有支持的样式字符串都以字符串数组的形式公开。colorNamesforegroundColorNamesbackgroundColorNames 的组合。

¥All supported style strings are exposed as an array of strings for convenience. colorNames is the combination of foregroundColorNames and backgroundColorNames.

如果你封装 Chalk 并需要验证输入,这将很有用:

¥This can be useful if you wrap Chalk and need to validate input:

import {modifierNames, foregroundColorNames} from 'chalk';

console.log(modifierNames.includes('bold'));
//=> true

console.log(foregroundColorNames.includes('pink'));
//=> false

样式

¥Styles

修饰符

¥Modifiers

  • reset - 重置当前样式。

    ¥reset - Reset the current style.

  • bold - 使文本变为粗体。

    ¥bold - Make the text bold.

  • dim - 使文本具有较低的不透明度。

    ¥dim - Make the text have lower opacity.

  • italic - 使文本变为斜体。(未得到广泛支持)

    ¥italic - Make the text italic. (Not widely supported)

  • underline - 在文本下方放置一条水平线。(未得到广泛支持)

    ¥underline - Put a horizontal line below the text. (Not widely supported)

  • overline - 在文本上方放置一条水平线。(未得到广泛支持)

    ¥overline - Put a horizontal line above the text. (Not widely supported)

  • inverse- 反转背景和前景色。

    ¥inverse- Invert background and foreground colors.

  • hidden - 打印文本但使其不可见。

    ¥hidden - Print the text but make it invisible.

  • strikethrough - 在文本中心放置一条水平线。(未得到广泛支持)

    ¥strikethrough - Puts a horizontal line through the center of the text. (Not widely supported)

  • visible- 仅当 Chalk 的颜色级别高于零时才打印文本。对于纯粹美观的东西很有用。

    ¥visible- Print the text only when Chalk has a color level above zero. Can be useful for things that are purely cosmetic.

颜色

¥Colors

  • black

  • red

  • green

  • yellow

  • blue

  • magenta

  • cyan

  • white

  • blackBright(别名:graygrey

    ¥blackBright (alias: gray, grey)

  • redBright

  • greenBright

  • yellowBright

  • blueBright

  • magentaBright

  • cyanBright

  • whiteBright

背景颜色

¥Background colors

  • bgBlack

  • bgRed

  • bgGreen

  • bgYellow

  • bgBlue

  • bgMagenta

  • bgCyan

  • bgWhite

  • bgBlackBright(别名:bgGraybgGrey

    ¥bgBlackBright (alias: bgGray, bgGrey)

  • bgRedBright

  • bgGreenBright

  • bgYellowBright

  • bgBlueBright

  • bgMagentaBright

  • bgCyanBright

  • bgWhiteBright

256 和 Truecolor 颜色支持

¥256 and Truecolor color support

Chalk 在支持的终端应用上支持 256 种颜色和 真彩色(1600 万种颜色)。

¥Chalk supports 256 colors and Truecolor (16 million colors) on supported terminal apps.

颜色从 1600 万 RGB 值下采样为终端模拟器支持的 ANSI 颜色格式(或通过将 {level: n} 指定为 Chalk 选项)。例如,配置为在级别 1(基本颜色支持)运行的 Chalk 将把 #FF0000(红色)的 RGB 值下采样为 31(红色的 ANSI 转义)。

¥Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying {level: n} as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

示例:

¥Examples:

  • chalk.hex('#DEADED').underline('Hello, world!')

  • chalk.rgb(15, 100, 204).inverse('Hello!')

这些模型的背景版本以 bg 为前缀,模块的第一级大写(例如,hex 表示前景色,bgHex 表示背景色)。

¥Background versions of these models are prefixed with bg and the first level of the module capitalized (e.g. hex for foreground colors and bgHex for background colors).

  • chalk.bgHex('#DEADED').underline('Hello, world!')

  • chalk.bgRgb(15, 100, 204).inverse('Hello!')

可以使用以下颜色模型:

¥The following color models can be used:

  • rgb - 示例:chalk.rgb(255, 136, 0).bold('Orange!')

    ¥rgb - Example: chalk.rgb(255, 136, 0).bold('Orange!')

  • hex - 示例:chalk.hex('#FF8800').bold('Orange!')

    ¥hex - Example: chalk.hex('#FF8800').bold('Orange!')

  • ansi256 - 示例:chalk.bgAnsi256(194)('Honeydew, more or less')

    ¥ansi256 - Example: chalk.bgAnsi256(194)('Honeydew, more or less')

浏览器支持

¥Browser support

自 Chrome 69 起,开发者控制台原生支持 ANSI 转义码。

¥Since Chrome 69, ANSI escape codes are natively supported in the developer console.

Windows

如果你使用的是 Windows,请帮自己一个忙,使用 Windows 终端 而不是 cmd.exe

¥If you're on Windows, do yourself a favor and use Windows Terminal instead of cmd.exe.

常见问题

¥FAQ

为什么不切换到较小的着色包?

¥Why not switch to a smaller coloring package?

Chalk 可能更大,但这是有原因的。它提供了更用户友好的 API、记录良好的类型、支持数百万种颜色,并涵盖了较小替代方案所遗漏的边缘情况。Chalk 成熟、可靠且经久耐用。

¥Chalk may be larger, but there is a reason for that. It offers a more user-friendly API, well-documented types, supports millions of colors, and covers edge cases that smaller alternatives miss. Chalk is mature, reliable, and built to last.

但除了技术方面之外,还有一些更关键的东西:信任和长期维护。我在开源字段活跃了十多年,并致力于维护 Chalk。较小的软件包现在可能看起来很有吸引力,但不能保证它们会长期存在,也不能保证它们不会随着时间的推移而变得恶意。

¥But beyond the technical aspects, there's something more critical: trust and long-term maintenance. I have been active in open source for over a decade, and I'm committed to keeping Chalk maintained. Smaller packages might seem appealing now, but there's no guarantee they will be around for the long term, or that they won't become malicious over time.

Chalk 可能也已经在你的依赖树中(因为有 100K+ 个包依赖于它),因此切换不会节省空间 - 事实上,它可能会增加空间。npm 会重复依赖,因此多个 Chalk 实例会变成一个,但在其旁边添加另一个包会增加你的整体大小。

¥Chalk is also likely already in your dependency tree (since 100K+ packages depend on it), so switching won’t save space—in fact, it might increase it. npm deduplicates dependencies, so multiple Chalk instances turn into one, but adding another package alongside it will increase your overall size.

如果目标是清理生态系统,那么放弃 Chalk 甚至不会产生任何影响。真正的问题在于具有非常深的依赖树的软件包(例如,包含大量 polyfill 的软件包)。Chalk 没有依赖。最好专注于有影响力的变化,而不是小优化。

¥If the goal is to clean up the ecosystem, switching away from Chalk won’t even make a dent. The real problem lies with packages that have very deep dependency trees (for example, those including a lot of polyfills). Chalk has no dependencies. It's better to focus on impactful changes rather than minor optimizations.

如果绝对包大小对你来说很重要,我还维护了 yoctocolors,这是最小的颜色包之一。

¥If absolute package size is important to you, I also maintain yoctocolors, one of the smallest color packages out there.

但较小的着色包有基准测试显示它速度更快

¥But the smaller coloring package has benchmarks showing it is faster

微基准测试存在缺陷 是因为它们在非现实的孤立场景中测量性能,通常会扭曲现实世界的性能。不要相信营销花言巧语。所有着色包都足够快。

¥Micro-benchmarks are flawed because they measure performance in unrealistic, isolated scenarios, often giving a distorted view of real-world performance. Don't believe marketing fluff. All the coloring packages are more than fast enough.

¥Related

维护者

¥Maintainers