Amazing CLIfor Terminal
Guide

Usage Patterns

Common integration patterns and best practices

Git2Docs Certified

Overview

This page covers the most common patterns for integrating Chalk into a Node.js application or browser bundle: importing the library, applying chained styles, controlling color levels, and structuring reusable themes. Understanding these patterns helps you produce clean, readable terminal output without managing raw ANSI escape sequences yourself. All examples assume an ESM project — Chalk is ESM-only and ships no CommonJS build.


Prerequisites

Before you begin, make sure you have:

  • Node.js ≥ 22 (CI tests Node 22 and 26; other versions are not tested)
  • A project configured for ES modules — either "type": "module" in package.json, or files using the .mjs extension
  • An ESM-compatible bundler if targeting a browser environment (Chalk selects a Chromium-aware color detector automatically via the package exports map)

Note on CommonJS: There is no CommonJS build. On Node.js ≥ 22.12, require('chalk') loads the ES module namespace and the default export is available as .default. On earlier Node 22 releases, require('chalk') throws ERR_REQUIRE_ESM.


Installation
  1. Add Chalk to your project using your preferred package manager:

    npm install chalk
    
    pnpm add chalk
    
    yarn add chalk
    
  2. Verify your package.json includes "type": "module" so Node.js treats your files as ES modules:

    {
      "type": "module"
    }
    
  3. Import Chalk in your code:

    import chalk from 'chalk';
    

Chalk has no runtime dependencies — ansi-styles and supports-color are vendored internally, so nothing extra is installed alongside the package.


Configuration

Chalk exposes one primary configuration surface: the color level, an integer from 0 to 3 that controls which ANSI escape sequences are emitted.

LevelDescription
0All colors disabled
1Basic color support (16 colors)
2256-color support
3Truecolor support (16 million colors)

Setting a value outside this range — or a non-integer — throws an error.

Automatic detection

By default, Chalk reads the color level from the runtime environment at import time. You do not need to configure anything for standard use.

CLI flags (override detection)

FlagEffect
--no-colorForces level 0 (no color)
--colorEnables color (level 1 or above)
--color=256Forces 256-color mode (level 2)
--color=16mForces Truecolor mode (level 3)

Environment variables (override detection)

VariableEffect
FORCE_COLOR=0Disables color (level 0)
FORCE_COLOR=1Sets level 1
FORCE_COLOR=2Sets level 2
FORCE_COLOR=3Sets level 3 (capped at 3)
FORCE_COLOR=trueEnables color at level 1 or above; lets detection set the exact level

Numeric FORCE_COLOR sets the level directly. --color=256 and --color=16m take precedence over a non-zero numeric FORCE_COLOR.

Setting the level programmatically

Avoid mutating chalk.level globally in reusable modules — it applies to every Chalk consumer in the process. Instead, create an isolated instance with the Chalk class:

import { Chalk } from 'chalk';

const customChalk = new Chalk({ level: 0 }); // colors off for this instance

Passing undefined or omitting level lets Chalk detect the level automatically.

Browser color detection

When bundled for a non-Node runtime, Chalk automatically uses a Chromium-aware detector:

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

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


Usage

Importing

Always import from the package name. The default export is a pre-configured chalk instance with auto-detected color level:

import chalk from 'chalk';

To import named exports (the Chalk class, stream-specific instances, or style name arrays), use named imports:

import chalk, { Chalk, chalkStderr, modifierNames, foregroundColorNames } from 'chalk';

Chaining styles

Build styled strings by chaining any combination of modifiers, foreground colors, background colors, and color model methods, then calling the final item as a function:

import chalk from 'chalk';

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

// Multiple chained styles
console.log(chalk.blue.bgRed.bold('Hello world!'));

// Mix styled and plain strings
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Pass multiple arguments — they are joined with a space
console.log(chalk.blue('Hello', 'World!', 'Foo', 'bar'));

Order within a chain generally does not matter; later styles take precedence when two styles conflict (e.g. chalk.red.yellow.green is equivalent to chalk.green).


Nesting styles

Pass a chalk-styled string as an argument inside another chalk call. Chalk correctly reopens interrupted escape sequences so nested colors don't bleed:

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!'
  )
);

Using with template literals

You can interpolate chalk-styled values in standard ES2015 template literals:

const name = 'Sindre';
console.log(`Hello ${chalk.green(name)}`);

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

Important: Do not use chalk as a tagged template literal (e.g. chalk.red`text ${val}`). Tagged template literals are not supported by core chalk. The chain returns a function that joins its arguments with spaces, so chalk.green`Hello ${name}` yields "Hello , Sindre" rather than interpolating correctly. Use the separate chalk-template package if you need tagged template literal support.


Extended color models

For terminals that support 256 or Truecolor, use rgb, hex, or ansi256. Chalk automatically downsamples to the detected level:

// Hex color
console.log(chalk.hex('#DEADED').bold('Bold gray!'));

// RGB color
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));

// 256-color palette index
console.log(chalk.ansi256(196)('Red from the 256-color palette'));

Background and underline variants follow the same prefix convention:

console.log(chalk.bgHex('#DEADED').underline('Hello, world!'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Hello!'));

// Underline color (only visible when an underline modifier is also applied)
console.log(chalk.underlineHex('#DEADED').underlineCurly('Hello, world!'));

Defining reusable themes

Capture a partially-applied chain in a variable to create a semantic style you can reuse throughout your application:

import chalk from 'chalk';

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

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

Isolated instances for libraries

If you are writing a reusable module, never mutate chalk.level directly — it is a global setting. Instead construct a private instance:

import { Chalk } from 'chalk';

const chalk = new Chalk({ level: 2 }); // 256-color, isolated to this module

Per-stream instances

Use chalkStderr when writing to stderr — it auto-detects color support for that stream independently of stdout:

import { chalkStderr } from 'chalk';

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

Using console.log string substitution

import chalk from 'chalk';

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

Validating style names at runtime

The exported name arrays let you validate user-supplied style strings without hard-coding the full list:

import { modifierNames, foregroundColorNames } from 'chalk';

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

Available arrays: modifierNames, foregroundColorNames, backgroundColorNames, underlineColorNames, and colorNames (the union of foregroundColorNames and backgroundColorNames).


Examples

Basic color and modifier chain

import chalk from 'chalk';

console.log(chalk.blue('Hello world!'));
console.log(chalk.blue.bgRed.bold('Hello world!'));
console.log(chalk.blue('Hello') + ' World' + chalk.red('!'));

Multiple arguments joined by space

import chalk from 'chalk';

console.log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

Nested styles

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 literal interpolation

import chalk from 'chalk';

const log = console.log;

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

Truecolor: hex and RGB

import chalk from 'chalk';

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

Background and underline color variants

import chalk from 'chalk';

console.log(chalk.bgHex('#DEADED').underline('Hello, world!'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Hello!'));

// Underline color — only visible when an underline modifier is applied
console.log(chalk.underlineHex('#DEADED').underlineCurly('Hello, world!'));
console.log(chalk.underlineRgb(15, 100, 204).underline('Hello!'));

256-color palette

import chalk from 'chalk';

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

Reusable semantic theme

import chalk from 'chalk';

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

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

console.log string substitution

import chalk from 'chalk';

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

Isolated instance with explicit color level

import { Chalk } from 'chalk';

const customChalk = new Chalk({ level: 0 });

console.log(customChalk.red('This prints without color (level 0)'));

Writing to stderr with chalkStderr

import { chalkStderr } from 'chalk';

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

Validating style names

import { modifierNames, foregroundColorNames } from 'chalk';

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

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

Per-character Truecolor (rainbow animation pattern)

The following pattern — drawn from the bundled examples/rainbow.js — shows how to combine chalk.hex() with computed hue values to apply a different color to each character:

import chalk from 'chalk';

// Apply a hex color per character, cycling through hues
function rainbow(string, offset) {
  const ignoreCharacters = /[^\u{0021}-\u{007E}]/gv;
  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 {
      // Convert HSL → hex externally, then pass to chalk.hex()
      characters.push(chalk.hex(hslToHex(hue, 100, 50))(character));
      hue = (hue + hueStep) % 360;
    }
  }

  return characters.join('');
}

hslToHex is not provided by Chalk; the original example uses the color-convert package for that conversion.


Troubleshooting

No colors appear in terminal output

Symptom: Chalk calls produce plain text with no styling.

Likely causes and fixes:

  • The detected color level is 0. Check whether FORCE_COLOR=0 is set in your environment, or whether --no-color is being passed to the Node.js process. Remove the flag or variable, or set FORCE_COLOR=1 (or higher) to force a minimum level.
  • You are piping output to a non-TTY (e.g. redirecting to a file). The supports-color detector returns level 0 for non-TTY streams. Use FORCE_COLOR=1 or the --color flag to override this when you need colored output in a piped context.
  • A manually constructed new Chalk({ level: 0 }) instance is being used. Confirm the instance's level property is non-zero.

ERR_REQUIRE_ESM when calling require('chalk')

Symptom: A CommonJS file throws Error [ERR_REQUIRE_ESM]: require() of ES Module … not supported.

Cause: Chalk is ESM-only. Node.js versions earlier than 22.12 cannot require() an ES module.

Fix:

  • Upgrade to Node.js ≥ 22.12, where require('chalk') loads the ES module namespace (access the default export as .default).
  • Or convert your consuming file to ESM (import chalk from 'chalk').

Tagged template literal produces garbled or missing interpolation

Symptom: chalk.green`Hello ${name}` prints something like Hello , Sindre instead of Hello Sindre.

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

Fix: Use the chalk-template package, which is specifically designed to provide tagged template literal support for Chalk.


Colors bleed across lines in macOS Terminal

Symptom: A styled multiline string causes the ANSI color to continue onto the next line unexpectedly.

Cause: Some macOS terminal emulators do not reset styles across newlines correctly.

Fix: Chalk handles this automatically by closing the style sequence before each newline and reopening it after — this is built into applyStyle. If you observe bleed, verify you are not constructing raw ANSI strings manually or combining Chalk output with raw escape sequences in a way that bypasses this logic.


level setter throws an error

Symptom: Setting chalk.level or passing a level option to new Chalk() throws Error: The \level` should be an integer from 0 to 3`.

Cause: The value passed is not a safe integer in the range 0–3 (e.g. a float, a string, null, or a number outside the range).

Fix: Pass only an integer: 0, 1, 2, or 3. Omit the option (or pass undefined) to let Chalk detect the level automatically.


Browser bundle shows no color output

Symptom: Chalk-styled strings appear unstyled in the browser developer console.

Cause: The browser color detector (selected automatically by the package exports map) returns level 0 for non-Chromium browsers and for environments with no navigator.

Fix:

  • Use a Chromium-based browser (Chrome 69+). ANSI escape codes are natively supported in the Chromium developer console since Chrome 69. Chromium brand version > 93 gives level 3 (Truecolor); any other Chrome/Chromium user agent gives level 1.
  • For non-Chromium browsers, construct an isolated instance and set the level explicitly: new Chalk({ level: 1 }).