UNPKG

13.4 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) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
13
14<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
15
16<br>
17
18---
19
20<div align="center">
21 <p>
22 <p>
23 <sup>
24 Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
25 </sup>
26 </p>
27 <sup>Special thanks to:</sup>
28 <br>
29 <br>
30 <a href="https://standardresume.co/tech">
31 <img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
32 </a>
33 <br>
34 <br>
35 <a href="https://retool.com/?utm_campaign=sindresorhus">
36 <img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/>
37 </a>
38 <br>
39 <br>
40 <a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
41 <div>
42 <img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
43 </div>
44 <b>All your environment variables, in one place</b>
45 <div>
46 <span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
47 <br>
48 <span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
49 </div>
50 </a>
51 <br>
52 <a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github">
53 <div>
54 <img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery">
55 </div>
56 </a>
57 </p>
58</div>
59
60---
61
62<br>
63
64## Highlights
65
66- Expressive API
67- Highly performant
68- Ability to nest styles
69- [256/Truecolor color support](#256-and-truecolor-color-support)
70- Auto-detects color support
71- Doesn't extend `String.prototype`
72- Clean and focused
73- Actively maintained
74- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
75
76## Install
77
78```console
79$ npm install chalk
80```
81
82## Usage
83
84```js
85const chalk = require('chalk');
86
87console.log(chalk.blue('Hello world!'));
88```
89
90Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
91
92```js
93const chalk = require('chalk');
94const log = console.log;
95
96// Combine styled and normal strings
97log(chalk.blue('Hello') + ' World' + chalk.red('!'));
98
99// Compose multiple styles using the chainable API
100log(chalk.blue.bgRed.bold('Hello world!'));
101
102// Pass in multiple arguments
103log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
104
105// Nest styles
106log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
107
108// Nest styles of the same type even (color, underline, background)
109log(chalk.green(
110 'I am a green line ' +
111 chalk.blue.underline.bold('with a blue substring') +
112 ' that becomes green again!'
113));
114
115// ES2015 template literal
116log(`
117CPU: ${chalk.red('90%')}
118RAM: ${chalk.green('40%')}
119DISK: ${chalk.yellow('70%')}
120`);
121
122// ES2015 tagged template literal
123log(chalk`
124CPU: {red ${cpu.totalPercent}%}
125RAM: {green ${ram.used / ram.total * 100}%}
126DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
127`);
128
129// Use RGB colors in terminal emulators that support it.
130log(chalk.keyword('orange')('Yay for orange colored text!'));
131log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
132log(chalk.hex('#DEADED').bold('Bold gray!'));
133```
134
135Easily define your own themes:
136
137```js
138const chalk = require('chalk');
139
140const error = chalk.bold.red;
141const warning = chalk.keyword('orange');
142
143console.log(error('Error!'));
144console.log(warning('Warning!'));
145```
146
147Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
148
149```js
150const name = 'Sindre';
151console.log(chalk.green('Hello %s'), name);
152//=> 'Hello Sindre'
153```
154
155## API
156
157### chalk.`<style>[.<style>...](string, [string...])`
158
159Example: `chalk.red.bold.underline('Hello', 'world');`
160
161Chain [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`.
162
163Multiple arguments will be separated by space.
164
165### chalk.level
166
167Specifies the level of color support.
168
169Color 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.
170
171If you need to change this in a reusable module, create a new instance:
172
173```js
174const ctx = new chalk.Instance({level: 0});
175```
176
177| Level | Description |
178| :---: | :--- |
179| `0` | All colors disabled |
180| `1` | Basic color support (16 colors) |
181| `2` | 256 color support |
182| `3` | Truecolor support (16 million colors) |
183
184### chalk.supportsColor
185
186Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
187
188Can 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.
189
190Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
191
192### chalk.stderr and chalk.stderr.supportsColor
193
194`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.
195
196## Styles
197
198### Modifiers
199
200- `reset` - Resets the current color chain.
201- `bold` - Make text bold.
202- `dim` - Emitting only a small amount of light.
203- `italic` - Make text italic. *(Not widely supported)*
204- `underline` - Make text underline. *(Not widely supported)*
205- `inverse`- Inverse background and foreground colors.
206- `hidden` - Prints the text, but makes it invisible.
207- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
208- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
209
210### Colors
211
212- `black`
213- `red`
214- `green`
215- `yellow`
216- `blue`
217- `magenta`
218- `cyan`
219- `white`
220- `blackBright` (alias: `gray`, `grey`)
221- `redBright`
222- `greenBright`
223- `yellowBright`
224- `blueBright`
225- `magentaBright`
226- `cyanBright`
227- `whiteBright`
228
229### Background colors
230
231- `bgBlack`
232- `bgRed`
233- `bgGreen`
234- `bgYellow`
235- `bgBlue`
236- `bgMagenta`
237- `bgCyan`
238- `bgWhite`
239- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
240- `bgRedBright`
241- `bgGreenBright`
242- `bgYellowBright`
243- `bgBlueBright`
244- `bgMagentaBright`
245- `bgCyanBright`
246- `bgWhiteBright`
247
248## Tagged template literal
249
250Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
251
252```js
253const chalk = require('chalk');
254
255const miles = 18;
256const calculateFeet = miles => miles * 5280;
257
258console.log(chalk`
259 There are {bold 5280 feet} in a mile.
260 In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
261`);
262```
263
264Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
265
266Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
267
268```js
269console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
270console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
271console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
272```
273
274Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
275
276All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
277
278## 256 and Truecolor color support
279
280Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
281
282Colors 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).
283
284Examples:
285
286- `chalk.hex('#DEADED').underline('Hello, world!')`
287- `chalk.keyword('orange')('Some orange text')`
288- `chalk.rgb(15, 100, 204).inverse('Hello!')`
289
290Background 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).
291
292- `chalk.bgHex('#DEADED').underline('Hello, world!')`
293- `chalk.bgKeyword('orange')('Some orange text')`
294- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
295
296The following color models can be used:
297
298- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
299- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
300- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
301- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
302- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
303- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
304- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
305- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
306
307## Windows
308
309If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
310
311## Origin story
312
313[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.
314
315## chalk for enterprise
316
317Available as part of the Tidelift Subscription.
318
319The 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)
320
321## Related
322
323- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
324- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
325- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
326- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
327- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
328- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
329- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
330- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
331- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
332- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
333- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
334- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
335- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
336- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
337
338## Maintainers
339
340- [Sindre Sorhus](https://github.com/sindresorhus)
341- [Josh Junon](https://github.com/qix-)