UNPKG

11.8 kBMarkdownView Raw
1<h1 align="center">
2 <br>
3 <br>
4 <img width="320" src="media/logo.svg" alt="Chalk">
5 <br>
6 <br>
7 <br>
8</h1>
9
10> Terminal string styling done right
11
12[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg)
13
14<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
15
16
17## Highlights
18
19- Expressive API
20- Highly performant
21- Ability to nest styles
22- [256/Truecolor color support](#256-and-truecolor-color-support)
23- Auto-detects color support
24- Doesn't extend `String.prototype`
25- Clean and focused
26- Actively maintained
27- [Used by ~46,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 1, 2019
28
29
30## Install
31
32```console
33$ npm install chalk
34```
35
36
37## Usage
38
39```js
40const chalk = require('chalk');
41
42console.log(chalk.blue('Hello world!'));
43```
44
45Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
46
47```js
48const chalk = require('chalk');
49const log = console.log;
50
51// Combine styled and normal strings
52log(chalk.blue('Hello') + ' World' + chalk.red('!'));
53
54// Compose multiple styles using the chainable API
55log(chalk.blue.bgRed.bold('Hello world!'));
56
57// Pass in multiple arguments
58log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
59
60// Nest styles
61log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
62
63// Nest styles of the same type even (color, underline, background)
64log(chalk.green(
65 'I am a green line ' +
66 chalk.blue.underline.bold('with a blue substring') +
67 ' that becomes green again!'
68));
69
70// ES2015 template literal
71log(`
72CPU: ${chalk.red('90%')}
73RAM: ${chalk.green('40%')}
74DISK: ${chalk.yellow('70%')}
75`);
76
77// ES2015 tagged template literal
78log(chalk`
79CPU: {red ${cpu.totalPercent}%}
80RAM: {green ${ram.used / ram.total * 100}%}
81DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
82`);
83
84// Use RGB colors in terminal emulators that support it.
85log(chalk.keyword('orange')('Yay for orange colored text!'));
86log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
87log(chalk.hex('#DEADED').bold('Bold gray!'));
88```
89
90Easily define your own themes:
91
92```js
93const chalk = require('chalk');
94
95const error = chalk.bold.red;
96const warning = chalk.keyword('orange');
97
98console.log(error('Error!'));
99console.log(warning('Warning!'));
100```
101
102Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
103
104```js
105const name = 'Sindre';
106console.log(chalk.green('Hello %s'), name);
107//=> 'Hello Sindre'
108```
109
110
111## API
112
113### chalk.`<style>[.<style>...](string, [string...])`
114
115Example: `chalk.red.bold.underline('Hello', 'world');`
116
117Chain [styles](#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`.
118
119Multiple arguments will be separated by space.
120
121### chalk.level
122
123Specifies the level of color support.
124
125Color 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.
126
127If you need to change this in a reusable module, create a new instance:
128
129```js
130const ctx = new chalk.Instance({level: 0});
131```
132
133| Level | Description |
134| :---: | :--- |
135| `0` | All colors disabled |
136| `1` | Basic color support (16 colors) |
137| `2` | 256 color support |
138| `3` | Truecolor support (16 million colors) |
139
140### chalk.supportsColor
141
142Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
143
144Can 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.
145
146Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
147
148### chalk.stderr and chalk.stderr.supportsColor
149
150`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
151
152
153## Styles
154
155### Modifiers
156
157- `reset` - Resets the current color chain.
158- `bold` - Make text bold.
159- `dim` - Emitting only a small amount of light.
160- `italic` - Make text italic. *(Not widely supported)*
161- `underline` - Make text underline. *(Not widely supported)*
162- `inverse`- Inverse background and foreground colors.
163- `hidden` - Prints the text, but makes it invisible.
164- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
165- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
166
167### Colors
168
169- `black`
170- `red`
171- `green`
172- `yellow`
173- `blue`
174- `magenta`
175- `cyan`
176- `white`
177- `blackBright` (alias: `gray`, `grey`)
178- `redBright`
179- `greenBright`
180- `yellowBright`
181- `blueBright`
182- `magentaBright`
183- `cyanBright`
184- `whiteBright`
185
186### Background colors
187
188- `bgBlack`
189- `bgRed`
190- `bgGreen`
191- `bgYellow`
192- `bgBlue`
193- `bgMagenta`
194- `bgCyan`
195- `bgWhite`
196- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
197- `bgRedBright`
198- `bgGreenBright`
199- `bgYellowBright`
200- `bgBlueBright`
201- `bgMagentaBright`
202- `bgCyanBright`
203- `bgWhiteBright`
204
205
206## Tagged template literal
207
208Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
209
210```js
211const chalk = require('chalk');
212
213const miles = 18;
214const calculateFeet = miles => miles * 5280;
215
216console.log(chalk`
217 There are {bold 5280 feet} in a mile.
218 In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
219`);
220```
221
222Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
223
224Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
225
226```js
227console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
228console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
229```
230
231Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
232
233All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
234
235
236## 256 and Truecolor color support
237
238Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
239
240Colors 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).
241
242Examples:
243
244- `chalk.hex('#DEADED').underline('Hello, world!')`
245- `chalk.keyword('orange')('Some orange text')`
246- `chalk.rgb(15, 100, 204).inverse('Hello!')`
247
248Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
249
250- `chalk.bgHex('#DEADED').underline('Hello, world!')`
251- `chalk.bgKeyword('orange')('Some orange text')`
252- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
253
254The following color models can be used:
255
256- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
257- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
258- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
259- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
260- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
261- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
262- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
263- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
264
265
266## Windows
267
268If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
269
270
271## Origin story
272
273[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
274
275
276## chalk for enterprise
277
278Available as part of the Tidelift Subscription.
279
280The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
281
282
283## Related
284
285- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
286- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
287- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
288- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
289- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
290- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
291- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
292- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
293- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
294- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
295- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
296- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
297- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
298- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
299
300
301## Maintainers
302
303- [Sindre Sorhus](https://github.com/sindresorhus)
304- [Josh Junon](https://github.com/qix-)