Key Concepts
Core abstractions and design patterns
Git2Docs CertifiedThis page explains the core abstractions that Chalk is built on: how style builders are constructed and chained, how color levels are detected and controlled, and where the ANSI escape sequences actually come from. Understanding these concepts helps you use the API correctly, avoid common pitfalls like misplaced tagged template literals, and make informed decisions when configuring Chalk for specific streams or environments.
The default chalk export and the Chalk class
When you import Chalk, the default export is a pre-configured function — not a plain object — that is ready to use immediately:
import chalk from 'chalk';
This default instance detects color support from stdout at module load time. Its color level is set once and applies globally to every consumer that holds a reference to it. If you need isolated color settings — for example, to style stderr output independently, or to disable color in a specific context without affecting the rest of your program — construct a separate instance using the Chalk class:
import { Chalk } from 'chalk';
const customChalk = new Chalk({ level: 0 }); // colors disabled
The Chalk constructor accepts an Options object with an optional level property. If you omit level or pass undefined, the level is auto-detected from the environment. Passing an invalid value (anything that is not an integer from 0 to 3) throws a plain Error with the message "The \level` should be an integer from 0 to 3"`.
Chainable style builders
Every style property or color method on a Chalk instance returns a new builder function that is cached on its parent. It never returns this. Each link in a chain is a distinct function whose prototype carries the full set of style properties, so chaining is composable at any depth:
const styled = chalk.bold.red; // a new builder, not chalk itself
styled('Hello'); // applies bold + red
Because each step produces a new builder, you can store intermediate chains as named style presets:
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500');
When you call a builder as a function, it accepts multiple string arguments and joins them with spaces. This is the idiomatic way to pass several values:
chalk.blue('Hello', 'World!', 'Foo');
// equivalent to: chalk.blue('Hello World! Foo')
Style conflict resolution — last style wins
When you chain conflicting styles of the same type (for example, two foreground colors), all ANSI open codes are emitted in the final string. Only the last conflicting style is visually applied, because it opens after the earlier ones:
chalk.yellow.redrenders red text —redopens last.chalk.red.yellowrenders yellow text —yellowopens last.
This means chalk.red.yellow.green is effectively equivalent to chalk.green. Earlier codes remain in the string but are overridden.
Color levels
Chalk maps terminal capability to an integer level that controls which ANSI sequences are emitted:
| Level | Description |
|---|---|
0 | All colors disabled |
1 | Basic 16-color support |
2 | 256-color support |
3 | Truecolor (16 million colors) |
The level is auto-detected at startup by inspecting TTY properties, environment variables, and CLI flags. You can read or override it on any Chalk instance:
chalk.level; // read the detected level
chalk.level = 1; // override (affects all consumers of this instance)
Assigning an invalid level throws the same Error as passing an invalid constructor option.
Colors specified with high-precision models (rgb, hex, ansi256) are downsampled to fit the detected level. For example, chalk.ansi256(196) becomes ANSI escape 91 (bright red) at level 1.
Environment-variable and flag overrides
Chalk respects several environment variables and CLI flags when detecting color support. The resolution order matters:
FORCE_COLOR=<n>(where<n>is a digit) sets the level directly to that integer, capped at 3. This replaces the result of--color/--no-colorflag processing.FORCE_COLOR=trueorFORCE_COLOR=(empty) enables color at level 1 or above and lets the level be detected normally.FORCE_COLOR=0orFORCE_COLOR=falsedisables color.--color=16mand--color=256take precedence over a non-zero numericFORCE_COLORto raise the level.--no-colorsets the flag result to 0, but a non-zeroFORCE_COLORoverrides it.COLORTERM=truecolorsignals level 3.TERM, CI-related variables (GITHUB_ACTIONS,CIRCLECI,TRAVIS, etc.), and platform detection are also consulted.
Chalk does not read or respect NO_COLOR.
supportsColor and supportsColorStderr
Chalk exposes the raw detection result for stdout and stderr as named exports:
import { supportsColor, supportsColorStderr } from 'chalk';
Each export is either a ColorInfo object (with a level property and boolean flags hasBasic, has256, has16m) or false when color is not detected. Always guard with a truthy check before accessing .level:
if (supportsColor) {
console.log('Color level:', supportsColor.level);
}
The chalkStderr named export is a separate Chalk instance configured from the stderr color detection result, equivalent to creating new Chalk({ level: supportsColorStderr ? supportsColorStderr.level : 0 }).
Vendored dependencies: ansi-styles and supports-color
Chalk has no runtime dependencies. The two libraries it relies on — ansi-styles and supports-color — are vendored internally under source/vendor/ and imported via the #ansi-styles and #supports-color import aliases respectively. This keeps your project's dependency graph clean.
source/vendor/ansi-styles owns every style property name (modifiers, foreground colors, background colors, underline colors) and the ANSI open/close escape sequence pairs that back them. source/vendor/supports-color performs the runtime environment inspection that produces the integer color level.
In non-Node environments (browser bundles), supports-color resolves to its browser entry point (source/vendor/supports-color/browser.js) via the default condition in package.json — not a browser condition. The browser detector inspects the Chromium brand version: a brand version above 93 gives level 3, any other Chrome/Chromium user agent gives level 1, and non-Chromium browsers or a missing navigator give level 0. Since Chrome 69, ANSI escape codes are natively supported in the developer console.
Tagged template literals
Core Chalk does not support tagged template literal syntax. Because a Chalk builder is a plain function, writing chalk.red\text ${val}`does not interpolate as expected. What actually happens is that the raw string array is coerced and the interpolated values are appended after a space — they are misplaced, not discarded. For example,chalk.green`Hello ${name}`yields"Hello , Sindre"rather than"Hello Sindre"`.
Use standard function call syntax instead:
chalk.red(`text ${val}`);
If you specifically need tagged template literal interpolation, use the separate chalk-template package, which is designed for that purpose.
CommonJS interop
Chalk is ESM-only — there is no CommonJS build. On Node.js ≥ 22.12, require('chalk') succeeds and returns the ES module namespace; access the default export via .default:
// Node.js >=22.12 only
const { default: chalk } = require('chalk');
On Node.js versions 22.0–22.11, require('chalk') throws ERR_REQUIRE_ESM.
Auto-detected color in a script
The simplest integration: import the default export and apply styles immediately. Color level is detected from the environment.
import chalk from 'chalk';
console.log(chalk.blue('Hello world!'));
Chaining multiple styles
Chain style properties and call the last one as a function. Each property access returns a new cached builder.
import chalk from 'chalk';
console.log(chalk.blue.bgRed.bold('Hello world!'));
Multiple arguments joined with spaces
Pass multiple values directly — they are joined with a single space.
import chalk from 'chalk';
console.log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
Storing styles as reusable presets
Capture a partially-built chain as a named variable and reuse it.
import chalk from 'chalk';
const error = chalk.bold.red;
const warning = chalk.hex('#FFA500');
console.log(error('Error!'));
console.log(warning('Warning!'));
Nesting styles
Nested calls restore the outer style after the inner one closes.
import chalk from 'chalk';
console.log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
Truecolor with rgb and hex
High-precision color methods accept arguments and return a builder. Downsampling to a lower level happens automatically.
import chalk from 'chalk';
console.log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
console.log(chalk.hex('#DEADED').bold('Bold gray!'));
Creating an isolated instance with new Chalk
Use the Chalk class when you need a fixed color level that does not affect the global default instance.
import { Chalk } from 'chalk';
const noColorChalk = new Chalk({ level: 0 });
console.log(noColorChalk.red('This will have no color applied'));
Guarding supportsColor before reading .level
supportsColor is either a ColorInfo object or false. Always check the value before accessing .level.
import { supportsColor } from 'chalk';
if (supportsColor) {
console.log('Detected color level:', supportsColor.level);
} else {
console.log('Color not supported');
}
Validating style names at runtime
Use the exported name arrays to validate style strings without hardcoding them.
import { modifierNames, foregroundColorNames } from 'chalk';
console.log(modifierNames.includes('bold'));
//=> true
console.log(foregroundColorNames.includes('pink'));
//=> false
Template literal interpolation — correct pattern
Core Chalk does not support tagged template syntax. Use a regular function call with a template literal instead.
import chalk from 'chalk';
const name = 'Sindre';
console.log(chalk.green(`Hello ${name}`));
Underline color (requires an underline modifier)
Underline colors are only visible when combined with an underline style.
import chalk from 'chalk';
console.log(chalk.underlineHex('#DEADED').underlineCurly('Hello, world!'));
console.log(chalk.underlineRgb(15, 100, 204).underline('Hello!'));
- Install and import — step-by-step guide to adding Chalk to your project and writing your first styled output.
- Apply chained styles — practical patterns for composing modifiers, foreground colors, background colors, and underline colors in a single expression.
chalk-template— the companion package that provides true tagged template literal support with correct interpolation, referenced in chalk-template on GitHub.chalkStderrand per-stream instances — how to stylestderroutput independently using the exportedchalkStderrinstance or a customnew Chalk({ level })instance.- Color level reference — a full table of environment variables (
FORCE_COLOR,COLORTERM), CLI flags (--color,--no-color,--color=256,--color=16m), and CI environment detection that influence the detected level.