---
title: Examples
product: amazing-cli
doc_type: guide
version: main
source: git2docs (code-derived, validation-filtered)
canonical: https://git2docs.com/wabam/docs/amazing-cli/chalk/examples
---

# Examples

_Real-world code examples_

## Overview

This page walks you through real-world usage of Chalk — from installation to advanced styling patterns. You will see how to chain styles, apply Truecolor and 256-color methods, create reusable style themes, isolate color levels with the `Chalk` class, and handle edge cases such as multiline strings and color-disabled environments. Each example is self-contained and runnable in any ESM-compatible Node.js ≥ 22 project.

## Prerequisites

Before you begin, make sure you have:

- **Node.js ≥ 22** — Chalk's `package.json` sets `"node": ">=22"`. CI tests run on Node 22 and 26; other versions are not tested.
- **An ESM-compatible project** — Chalk is ESM-only (`"type": "module"` in `package.json`). Your entry file must use `import`, or your `package.json` must declare `"type": "module"`.
- **npm, pnpm, or yarn** — any of these can install the package.
- *(Optional)* **`chalk-template`** — only needed if you want tagged template literal support with interpolation. Core Chalk does not support `chalk.red\`text ${val}\`` as a tagged template.

## Installation

1. Add Chalk to your project:

   ```sh
   npm install chalk
   ```

   Or with pnpm:

   ```sh
   pnpm add chalk
   ```

   Or with yarn:

   ```sh
   yarn add chalk
   ```

2. Import the default export in your ESM file:

   ```js
   import chalk from 'chalk';
   ```

   Chalk has no runtime dependencies — `ansi-styles` and `supports-color` are vendored internally, so your dependency graph stays clean.

3. *(Node ≥ 22.12 only — CommonJS interop)* On Node.js ≥ 22.12, `require('chalk')` loads the ES module namespace. Access the default export via `.default`:

   ```js
   // CommonJS — only works on Node.js ≥ 22.12
   const chalk = require('chalk').default;
   ```

   On earlier Node 22 releases, `require('chalk')` throws `ERR_REQUIRE_ESM`. Use `import()` or upgrade Node.

## Configuration

### Color level

Chalk automatically detects the host terminal's color capability and sets an integer level from 0 to 3:

| Level | Meaning |
|:---:|:---|
| `0` | Colors disabled |
| `1` | Basic 16-color support |
| `2` | 256-color support |
| `3` | Truecolor (16 million colors) |

Both the `level` option passed to `new Chalk({ level })` and the `chalk.level` property enforce this range. Passing anything outside 0–3 (or a non-integer) throws an error.

### Overriding level at runtime

Use environment variables or CLI flags to force a specific level without changing code:

| Mechanism | Effect |
|---|---|
| `FORCE_COLOR=0` | Disable color (level 0) |
| `FORCE_COLOR=1` | Force level 1 |
| `FORCE_COLOR=2` | Force level 2 |
| `FORCE_COLOR=3` | Force level 3 |
| `FORCE_COLOR=true` (or empty) | Enable color at level 1 or above; lets the terminal raise it higher |
| `--no-color` flag | Disable color |
| `--color` flag | Enable color |
| `--color=256` flag | Force 256-color mode |
| `--color=16m` flag | Force Truecolor mode |

Numeric `FORCE_COLOR` values are capped at 3. `--color=256` and `--color=16m` take precedence over a non-zero numeric `FORCE_COLOR`.

### Creating an isolated instance

Setting `chalk.level` globally affects every consumer of the same module instance. For per-stream or per-context control, create an isolated instance with the `Chalk` constructor instead:

```js
import { Chalk } from 'chalk';

const noColor = new Chalk({ level: 0 });
const truecolor = new Chalk({ level: 3 });
```

Omit the `level` option (or pass `undefined`) to have the level auto-detected for that instance.

### Browser environments

When bundled for a non-Node runtime, Chalk automatically uses a browser-specific color detector. The detector inspects the Chromium brand version via `navigator.userAgentData`:

- **Chromium brand version > 93** → level 3 (Truecolor)
- **Any other Chrome/Chromium user agent** → level 1
- **No `navigator`, or non-Chromium browser** → level 0

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

## Usage

### Basic styling

Import `chalk` and chain one or more style names, then call the result with your string:

```js
import chalk from 'chalk';

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

### Chaining multiple styles

Chain as many modifiers, foreground colors, and background colors as you need. Later styles take precedence when two colors of the same type conflict — `chalk.red.yellow.green` resolves to `chalk.green`:

```js
import chalk from 'chalk';

const log = console.log;

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

// Multiple styles in one chain
log(chalk.blue.bgRed.bold('Hello world!'));

// Multiple arguments — joined with a space
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
```

### Nesting styles

Pass a styled string as an argument to another chalk call. Chalk correctly reopens the outer style after the inner style closes:

```js
import chalk from 'chalk';

console.log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

console.log(chalk.green(
  'I am a green line ' +
  chalk.blue.underline.bold('with a blue substring') +
  ' that becomes green again!'
));
```

### Template literals (string interpolation)

Use standard ES2015 template literals — not tagged templates — to interpolate chalk-styled values:

```js
import chalk from 'chalk';

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

> **Note:** `chalk.red\`text ${val}\`` (tagged template syntax) does **not** interpolate as expected — it joins the raw string array. Use the [`chalk-template`](https://github.com/chalk/chalk-template) package if you need tagged template literal support with interpolation.

### Reusable style themes

Assign a partially-applied chalk chain to a variable to create a named style:

```js
import chalk from 'chalk';

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

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

### console.log string substitution

Chalk-styled strings work with Node's `console.log` `%s` substitution:

```js
import chalk from 'chalk';

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

### Truecolor and 256-color methods

Use `rgb`, `hex`, or `ansi256` for extended color support. Chalk automatically downsamples to the detected terminal level:

```js
import chalk from 'chalk';

// Hex foreground + underline
console.log(chalk.hex('#DEADED').underline('Hello, world!'));

// RGB foreground + inverse
console.log(chalk.rgb(15, 100, 204).inverse('Hello!'));

// Background variants — prefix with `bg`
console.log(chalk.bgHex('#DEADED').underline('Hello, world!'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Hello!'));

// 256-color background
console.log(chalk.bgAnsi256(194)('Honeydew, more or less'));
```

### Disabling color for a specific context

Create an isolated instance at level 0 to strip all ANSI codes — useful for log files or pipes:

```js
import { Chalk } from 'chalk';

const plain = new Chalk({ level: 0 });
console.log(plain.red('This will appear unstyled'));
```

### Styling stderr separately

Import `chalkStderr`, which is auto-configured against the `stderr` stream's color support:

```js
import { chalkStderr } from 'chalk';

process.stderr.write(chalkStderr.red('Something went wrong\n'));
```

## Examples

### Example 1 — Hello world

The simplest possible usage: a single color applied to a string.

```js
import chalk from 'chalk';

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

---

### Example 2 — Chained modifiers

Combine a foreground color, a background color, and a text modifier in a single chain:

```js
import chalk from 'chalk';

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

---

### Example 3 — Nested styles

Nest one styled string inside another. Chalk re-opens the outer style after the inner close sequence:

```js
import chalk from 'chalk';

console.log(chalk.green(
  'I am a green line ' +
  chalk.blue.underline.bold('with a blue substring') +
  ' that becomes green again!'
));
```

---

### Example 4 — Reusable named styles

Capture a chalk chain in a variable to create a lightweight theme:

```js
import chalk from 'chalk';

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

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

---

### Example 5 — Truecolor hex and RGB

Apply arbitrary colors using `hex` and `rgb`. Chalk downsamples automatically when the terminal supports fewer colors:

```js
import chalk from 'chalk';

console.log(chalk.hex('#DEADED').underline('Hello, world!'));
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
console.log(chalk.hex('#DEADED').bold('Bold gray!'));
```

---

### Example 6 — 256-color background

Use `bgAnsi256` to pick from the 256-color palette:

```js
import chalk from 'chalk';

console.log(chalk.bgAnsi256(194)('Honeydew, more or less'));
```

---

### Example 7 — Template literal interpolation

Interpolate chalk-styled values inside standard ES2015 template literals:

```js
import chalk from 'chalk';

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

---

### Example 8 — console.log string substitution

Chalk values compose naturally with Node's `%s` substitution:

```js
import chalk from 'chalk';

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

---

### Example 9 — Isolated instance with explicit level

Use the `Chalk` constructor to create an instance that is unaffected by global `chalk.level` changes:

```js
import { Chalk } from 'chalk';

const customChalk = new Chalk({ level: 0 }); // no color
console.log(customChalk.red('This will appear unstyled'));
```

---

### Example 10 — Validating style names at runtime

Use the exported name arrays to validate user-supplied style strings:

```js
import { modifierNames, foregroundColorNames } from 'chalk';

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

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

---

### Example 11 — Animated rainbow (using the `hex` color model)

This example from the repository demonstrates `chalk.hex()` combined with HSL→hex color conversion and an animated log-update loop. It requires the `color-convert` and `log-update` packages as dev/peer dependencies:

```js
import { setTimeout as delay } from 'node:timers/promises';
import convertColor from 'color-convert';
import updateLog from 'log-update';
import chalk from 'chalk';

const ignoreCharacters = /[^\u{0021}-\u{007E}]/gv;

function rainbow(string, offset) {
  if (!string || string.length === 0) {
    return string;
  }

  const hueStep = 360 / string.replaceAll(ignoreCharacters, '').length;

  let hue = offset % 360;
  const characters = [];
  for (const character of string) {
    if (ignoreCharacters.test(character)) {
      characters.push(character);
    } else {
      characters.push(chalk.hex(convertColor.hsl.hex(hue, 100, 50))(character));
      hue = (hue + hueStep) % 360;
    }
  }

  return characters.join('');
}

async function animateString(string) {
  for (let index = 0; index < 360 * 5; index++) {
    updateLog(rainbow(string, index));
    await delay(2);
  }
}

console.log();
await animateString('We hope you enjoy Chalk! <3');
console.log();
```

Each character is colored by converting an HSL hue angle to a hex code with `chalk.hex(...)`, cycling through the full spectrum across the string.

---

### Example 12 — Applying a style to every key dynamically

This pattern (from the repository's screenshot generator) iterates over style keys and applies each one to a string:

```js
import process from 'node:process';
import chalk from 'chalk';
import { colorNames } from 'chalk';

for (const key of colorNames) {
  process.stdout.write(chalk[key](key) + ' ');
}
```

## Troubleshooting

### No color output — everything appears plain

**Symptom:** Chalk calls produce no visible color in the terminal.

**Likely causes and fixes:**

- **Color level auto-detected as 0.** The terminal or pipe does not advertise color support. Set `FORCE_COLOR=1` (or `2`/`3`) in your environment to override:
  ```sh
  FORCE_COLOR=1 node your-script.js
  ```
- **`--no-color` flag is active.** Remove `--no-color` from your command, or unset any wrapper that injects it.
- **Explicit `level: 0` on an instance.** If you created a `new Chalk({ level: 0 })` instance, it will never emit color by design. Change the level or use the default `chalk` export.

---

### `ERR_REQUIRE_ESM` when using `require('chalk')`

**Symptom:** `Error [ERR_REQUIRE_ESM]: require() of ES Module … not supported`

**Cause:** You are running Node.js < 22.12. On those releases, CommonJS `require()` cannot load ES modules.

**Fix:** Upgrade to Node.js ≥ 22.12, which allows `require('chalk')` to return the ES module namespace (access the default export via `.default`). Alternatively, convert your file to ESM and use `import chalk from 'chalk'`.

---

### Tagged template literals produce garbled or incomplete output

**Symptom:** `chalk.red\`Hello ${name}\`` prints something like `Hello , Sindre` instead of the expected interpolated string.

**Cause:** Core Chalk does not support tagged template literals. When called as a tag, Chalk's builder receives the raw string array and joins arguments with spaces, losing interpolated values.

**Fix:** Install and use the [`chalk-template`](https://github.com/chalk/chalk-template) package, which is purpose-built for tagged template literal support:
```sh
npm install chalk-template
```
```js
import chalkTemplate from 'chalk-template';

console.log(chalkTemplate`Hello {red ${name}}`);
```

---

### `chalk.level` change affects other modules unexpectedly

**Symptom:** Setting `chalk.level = 0` in one file silences color output in an unrelated module.

**Cause:** The default `chalk` export is a module-level singleton. Setting `.level` on it is a global mutation.

**Fix:** Create an isolated instance with the `Chalk` constructor and use it locally:
```js
import { Chalk } from 'chalk';

const localChalk = new Chalk({ level: 0 });
```
This leaves the shared default instance and all other consumers unaffected.

---

### Colors look wrong in browser DevTools

**Symptom:** Colors appear, but at the wrong fidelity (e.g., only 16 colors instead of Truecolor).

**Cause:** The browser color detector checks the Chromium brand version. Chromium brand version > 93 enables level 3; any other Chrome/Chromium user agent gets level 1; non-Chromium browsers or environments without `navigator` get level 0.

**Fix:** Verify you are running Chrome 94+ (which reports a Chromium brand version > 93). Note that ANSI escape codes in the developer console have been natively supported since Chrome 69.
