BeautifulCLITerminal string styling done right — a chainable, zero-dependency library for adding color and style to Node.js CLI output.
Guide

Installation

Cover npm installation, the Node.js 16+ requirement, and the ESM-only constraint of Chalk 5. Show the canonical import statement. Warn clearly that require('chalk') throws in v5 and direct CommonJS users to pin chalk@4 or migrate to ESM.


Overview

This page walks you through installing Chalk 5, verifying your environment meets the Node.js 16+ requirement, and importing Chalk correctly using ESM. Understanding these constraints matters because Chalk 5 is ESM-only — attempting to load it with require() will throw a runtime error. If your project is still on CommonJS, this page also explains your options so you can make an informed choice before writing any code.


Prerequisites

Before installing Chalk, confirm your environment meets the following requirements:

  • Node.js 16 or later — Chalk 5 requires Node.js 16+. Earlier Node.js versions (including 12 and 14) are not supported by Chalk 5.
  • ESM-compatible module system — Your project must use ES modules ("type": "module" in package.json, or .mjs file extensions). Chalk 5 cannot be loaded with require().
  • A package manager — npm, yarn, or pnpm all work.
  • TypeScript (optional) — Chalk ships with bundled type definitions, so no separate @types/chalk package is needed.

Installation
  1. Install Chalk from the npm registry.

    npm install chalk
    

    Or, if you use yarn or pnpm:

    yarn add chalk
    
    pnpm add chalk
    
  2. Confirm your package.json declares ES module mode.

    Chalk 5 is ESM-only. Your project must opt in to ES modules before you can import Chalk. Open your package.json and ensure the following field is present:

    {
      "type": "module"
    }
    

    Alternatively, name your entry file with the .mjs extension instead of .js.

  3. Import Chalk using the ESM import statement.

    import chalk from 'chalk';
    

    That single import gives you access to the full Chalk API. You are now ready to style terminal output.

CommonJS users: If your project uses require() and you cannot migrate to ESM right now, pin Chalk to version 4 instead:

npm install chalk@4

Chalk 4 supports CommonJS and is a stable, maintained release. When you are ready to move to ESM, upgrade to Chalk 5 and replace require('chalk') with import chalk from 'chalk'.


Configuration

Chalk requires no configuration file. Its primary runtime setting is the color level, which controls how many colors Chalk uses when generating ANSI escape codes.

Color level

Chalk automatically detects the color capability of the current terminal and sets its level accordingly. You can read or override the level at runtime via the chalk.level property.

LevelConstant descriptionColors available
0DisabledNo color output — plain text only
1Basic16 foreground and background colors
2256-color256 indexed colors (ansi256)
3Truecolor~16 million colors via rgb() and hex()

When the terminal supports fewer colors than you request, Chalk degrades gracefully — for example, a Truecolor rgb() call is downsampled to the nearest 256-color index, then to the nearest basic color, depending on the detected level.

Overriding the level globally (suitable only for top-level application code, not reusable libraries):

import chalk from 'chalk';

chalk.level = 1; // Force basic 16-color output

Overriding the level for an isolated instance (recommended for libraries and test suites):

import { Chalk } from 'chalk';

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

Using new Chalk({ level }) ensures your override does not affect any other code that consumes the shared default chalk instance.

Environment variable overrides

You can force a specific color level from outside the process without changing code:

VariableEffect
FORCE_COLOR=0Disables color (level 0)
FORCE_COLOR=1Forces basic 16-color mode (level 1)
FORCE_COLOR=2Forces 256-color mode (level 2)
FORCE_COLOR=3Forces Truecolor mode (level 3)

FORCE_COLOR takes precedence over all other color-support checks, including terminal auto-detection. This is particularly useful in CI pipelines where terminal detection may fail.

FORCE_COLOR=3 node my-script.js

Usage

Once Chalk is installed and imported, you style a string by chaining one or more style methods on the chalk object and passing your string as the final argument.

Apply a single style

import chalk from 'chalk';

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

Chain multiple styles

Calling methods one after another applies all of them to the string. The order you write them does not affect precedence except when two methods conflict (for example, two foreground colors), in which case the last one wins.

import chalk from 'chalk';

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

Mix styled and unstyled text

Because each Chalk call returns a plain string, you can concatenate styled and normal strings freely:

import chalk from 'chalk';

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

Use RGB or hex colors

When your terminal supports Truecolor (level 3), you can specify any color precisely:

import chalk from 'chalk';

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

Chalk automatically downsamples these values if the terminal supports fewer than 16 million colors.

Define reusable theme styles

Because a partially-applied chain is itself a callable, you can store styles as named variables and reuse them throughout your application:

import chalk from 'chalk';

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

console.log(error('Build failed'));
console.log(warning('Deprecated API used'));
console.log(success('Tests passed'));

Pass multiple arguments

Chalk accepts multiple string arguments and joins them with a space, matching the behavior of console.log:

import chalk from 'chalk';

console.log(chalk.blue('Hello', 'World!', 'from', 'Chalk'));
// => Hello World! from Chalk  (all in blue)

Use 256-color mode

import chalk from 'chalk';

console.log(chalk.ansi256(194)('Soft honeydew green'));

Examples

Example 1 — Basic color and modifier

import chalk from 'chalk';

console.log(chalk.green('Success:'), 'File written.');
console.log(chalk.red.bold('Error:'), 'Permission denied.');
console.log(chalk.yellow.italic('Warning:'), 'Disk space low.');

Expected output (in a color-capable terminal):

Success: File written.
Error: Permission denied.
Warning: Disk space low.

The words Success:, Error:, and Warning: each appear in green, bold-red, and italic-yellow respectively; the rest of each line is unstyled.


Example 2 — Nested styles

import chalk from 'chalk';

console.log(
  chalk.green(
    'I am green, ' +
    chalk.blue.underline.bold('but this part is blue and bold') +
    ', and I am green again.'
  )
);

Expected output:

I am green, but this part is blue and bold, and I am green again.

Nesting resets the inner style at the closing boundary and restores the outer style automatically.


Example 3 — Truecolor with rgb() and hex()

import chalk from 'chalk';

console.log(chalk.rgb(255, 136, 0).bold('Orange alert!'));
console.log(chalk.hex('#00BFFF').underline('Deep sky blue'));
console.log(chalk.bgRgb(15, 100, 204).inverse('Blue background'));

Expected output (Truecolor terminal):

Orange alert!
Deep sky blue
Blue background

On terminals that support fewer colors, Chalk silently downsamples the RGB values to the closest available color.


Example 4 — Reusable theme

import chalk from 'chalk';

const label = chalk.bold.cyan;
const value = chalk.white;

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

Expected output:

CPU:  90%
RAM:  40%
DISK: 70%

Example 5 — Isolated Chalk instance for a library

When writing a reusable module, use new Chalk({ level }) to avoid interfering with the host application's global color settings:

import { Chalk } from 'chalk';

const chalk = new Chalk({ level: 2 }); // Always use 256-color mode

export function renderBanner(text) {
  return chalk.ansi256(226).bold(text); // Bright yellow
}

Expected output when the consuming app calls renderBanner('My Tool v1.0'):

My Tool v1.0

Rendered in bold 256-color yellow, regardless of what the host application has set on its own chalk instance.


Troubleshooting

Error [ERR_REQUIRE_ESM]: require() of ES Module … chalk

Symptom: Your Node.js process crashes immediately with an ERR_REQUIRE_ESM error when starting.

Cause: You are loading Chalk 5 with require('chalk') in a CommonJS module. Chalk 5 is ESM-only and cannot be require()-d.

Fix — Option A (migrate to ESM): Add "type": "module" to your package.json and replace require('chalk') with:

import chalk from 'chalk';

Fix — Option B (stay on CommonJS): Downgrade to Chalk 4, which fully supports CommonJS:

npm install chalk@4

Then keep your existing require('chalk') calls unchanged.


No colors appear in the terminal output

Symptom: Chalk calls succeed without errors, but the output is plain text with no color.

Cause: Chalk's auto-detection set level to 0 because the terminal reported no color support. This commonly happens in CI environments, piped output, or terminals that do not advertise ANSI support.

Fix: Set FORCE_COLOR to enable the color level you need:

FORCE_COLOR=1 node my-script.js   # Basic 16 colors
FORCE_COLOR=3 node my-script.js   # Truecolor

Or, in code (for top-level app scripts only — not libraries):

import chalk from 'chalk';
chalk.level = 1;

Colors look wrong or washed out

Symptom: Colors display, but rgb() or hex() values do not match what you specified — they appear as a nearby basic color.

Cause: Your terminal is operating at color level 1 (16 colors) or level 2 (256 colors). Chalk correctly downsamples Truecolor values to the nearest supported color.

Fix: Verify your terminal supports Truecolor and force level 3 if it does:

FORCE_COLOR=3 node my-script.js

If your terminal genuinely does not support Truecolor, the downsampled output is the correct behavior and cannot be changed without a better terminal.


new chalk.Instance() throws TypeError: chalk.Instance is not a constructor

Symptom: Code that worked in an older Chalk version fails with a TypeError when calling new chalk.Instance().

Cause: chalk.Instance was removed in Chalk 5. The API has changed.

Fix: Import the Chalk class as a named export and construct your instance with it:

import { Chalk } from 'chalk';

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

Tagged template literals like chalk`{red Hello}` throw or produce literal braces

Symptom: The tagged template syntax does not colorize text and either throws or outputs {red Hello} verbatim.

Cause: The built-in tagged template literal syntax was removed in Chalk 5.

Fix: Install the chalk-template package, which provides this functionality as a separate, opt-in module:

npm install chalk-template

Then update your import:

import chalkTemplate from 'chalk-template';

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