包详细信息

ansis

webdiscus12.5mISC4.0.0

ANSI color lib

ansi, colors, cli

自述文件

ansis

[ANSI S]tyles

npm node Test codecov downloads install size

ANSI color library for use in CI environments, terminals, and Chromium-based browsers.\ Ansis is focused on small size and speed while providing rich functionality and handling edge cases.

[!WARNING]

Version 4 introduces new features and breaking changes.\ Please follow the migration guide to upgrade.

🚀 Getting Started ⚖️ AlternativesWhy Ansis 🔄 Switch from 🔧Compatibility

Ansis demo

Open in StackBlitz

💡 Features

Install

npm install ansis

🛠️ Usage

import ansis, { red, bold, fg, hex, rgb } from 'ansis';

console.log(ansis.bold('file.txt'));
console.log(red`Error: ${bold.cyan(file)} not found!`);
console.log(bold.bgRed`ERROR`);
console.log(fg(208)`Orange`);
console.log(rgb(224, 17, 95)`Ruby`);
console.log(hex('#FF75D1').bold.underline('Pink'));

console.log(ansis.strip(red('Text'))); // Output plain text without ANSI codes

⚖️ Alternatives

The most popular ANSI libraries, similar to Ansis:

chalk, picocolors, colorette, kleur, ansi-colors, kolorist, cli-color, colors-cli, colors.js, tinyrainbow

Compare features 🧩 Handling edge cases 📦 Compare package sizes 📊 Benchmarks

Why use Ansis

As of 2025, two of the smallest and fastest ANSI libraries are Ansis and Picocolors. Both are recommended by the ES Tooling community as modern replacements for older, larger libraries.

📦 Unpacked size

The package size in node_modules directory:

  • picocolors: 6.37 kB (not minimized) - A micro library with basic features.
  • аnsis: 5.71 kB (minimized) - A powerful library with a rich set of features.
  • chalk: 44.2 kB (not minimized) - Provides similar functionality to Ansis.

⚡ Performance

  • picocolors: The fastest when applying a single style (e.g., red) only.
  • аnsis: The fastest when applying two or more styles (e.g., red + bgWhite).
  • chalk: Slower than both Ansis and Picocolors in all use cases.

[!CAUTION] Picocolors doesn't handle important edge cases, so it is the fastest.

Picocolors is faster only in a simple micro-benchmark, which does not reflect real world usage.\ In a more complex benchmark, Ansis is much closer to Picocolors results or even faster.

🧩 Edge cases

Absent, undefined or null arguments

Ansis handles these cases correctly.

ansis.red()          // ✅ ''
chalk.red()          // ✅ ''
pico.red()           // ❌ \e[31mundefined\e[39m

ansis.red(undefined) // ✅ ''
chalk.red(undefined) // ❌ \e[31mundefined\e[39m
pico.red(undefined)  // ❌ \e[31mundefined\e[39m

ansis.red(null)      // ✅ ''
chalk.red(null)      // ❌ \e[31mnull\e[39m
pico.red(null)       // ❌ \e[31mnull\e[39m

ansis.reset()        // ✅ \e[0m
chalk.reset()        // ❌ ''
pico.reset()         // ❌ \e[0mundefined\e[0m

See more details about handling input arguments in various libraries.

Empty string

Ansis and Chalk handle this case and return an empty string without ANSI codes as expected.\ However, Picocolors doesn't handle this case.

ansis.red('')          // ✅ ''
chalk.red('')          // ✅ ''
pico.red('')           // ❌ \e[31m\e[39m

Break style at New Line

Ansis and Chalk add a style break at each new line to correctly display multi-line text.\ However, Picocolors doesn't handle this case.

ansis.bgRed('\n ERROR \n') + ansis.cyan('The file not found!') // ✅
chalk.bgRed('\n ERROR \n') + chalk.cyan('The file not found!') // ✅
pico.bgRed('\n ERROR \n') + pico.cyan('The file not found!')   // ❌

Break style at New Line

Nested template strings

Only Ansis handles this very useful use case.

ansis.red`R ${ansis.green`G ${ansis.blue`B`} G`} R` // ✅
chalk.red`R ${chalk.green`G ${chalk.blue`B`} G`} R` // ❌
pico.red`R ${pico.green`G ${pico.blue`B`} G`} R`    // ❌

Nested template strings

🔧 Maintenance

As of 2025, only Ansis, Chalk, and Picocolors are actively maintained, unlike many other libraries:

🤔 Which One Should You Use?

  • If you only use a single style, e.g., red('foo'), Picocolors is the best solution.

  • However, if you need more, like combining multiple styles (e.g., red + bold + bgWhite),\ 256 colors, Truecolor, or support for a wide range of environments, then Ansis is the better choice.

Checklist:

Explore the list of features, package sizes, and benchmarks compared to similar libraries.

[!TIP]

To keep your code clean and readable:

  • Use the chained syntax provided by libraries like ansis and `chalk
  • Avoid nested calls, as they are much slower and less readable than the chained syntax.

Usage examples

import ansis, { red, green, cyan } from 'ansis' // ✅✅ supports both default and named imports
import chalk from 'chalk'                       // ✅❌ doesn't support named import
import pico from 'picocolors'                   // ✅❌ doesn't support named import

ansis.red('Error')                         //      ansis ❌ slower than picocolors
chalk.red('Error')                         //      chalk ❌ slower than ansis
pico.red('Error')                          // picocolors ✅ fastest

red.bold.bgWhite`Error`                    //      ansis ✅✅✅ fastest, short, readable
chalk.red.bold.bgWhite('Error')            //      chalk ❌☑️✅ slower, short, readable
pico.red(pico.bold(pico.bgWhite('Error'))) // picocolors ❌❌❌ slowest, long, unreadable

green`Create ${blue.bold`React`} app.`                     //      ansis ✅ usability 😊
chalk.green(`Create ${chalk.blue.bold('React')} app.`)     //      chalk ☑️ usability 🙂
pico.green(`Create ${pico.blue(pico.bold('React'))} app.`) // picocolors ❌ usability 🥴

[!TIP] Ansis supports nested template strings, so you can colorize text without using parentheses.


↑ top

Default and named import

ESM

// Default import
import ansis from 'ansis';
// Named imports
import { red, green, bold, dim } from 'ansis';

CommonJS

// Default import
const ansis = require('ansis');
// Named imports
const { red, green, bold, dim } = require('ansis');

Tagged template literals

[!TIP] Using template literals you can omit parentheses red(`error`)red`error` to keep your code clean and readable.

import { cyan, red } from 'ansis';

let file = '/path/to/file.txt';

red`Error: File ${cyan(file)} not found!`;

Using sequences

Ansis processes tagged template literals the same way as normal strings.

red('Hello\nWorld');
red`Hello\nWorld`;

Output (two lines in red):

Hello
World

To preserve \n, \t, \p and similar sequences as literal, escape them with a backslash (\):

red('prev\\next');
red`prev\\next`;

Output (one line in red):

prev\next

Nested template literals

Ansis correctly renders nested tagged template strings.

import { green, red, yellow } from 'ansis';

red`Red ${yellow`Yellow ${green`Green`} Yellow`} Red`;

red`Error: ${yellow`Module ${green`ansis`} is missing!`} Installation required.`;

Chained syntax

All colors, styles and functions are chainable. Each color or style can be combined in any order.

import { red, bold, italic, hex } from 'ansis';

red.bold`text`;
hex('#FF75D1').bgCyan.bold`text`;
bold.bgHex('#FF75D1').cyan`text`;
italic.bold.yellow.bgMagentaBright`text`;

↑ top

ANSI Styles

dim bold italic underline strikethrough inverse visible hidden reset

ANSI 16 colors

There are 16 basic colors: 8 standard and 8 bright variants.

Example Color Background Bright Example Bright Color Bright Background
black bgBlack gray bgGray
red bgRed redBright bgRedBright
green bgGreen greenBright bgGreenBright
yellow bgYellow yellowBright bgYellowBright
blue bgBlue blueBright bgBlueBright
magenta bgMagenta magentaBright bgMagentaBright
cyan bgCyan cyanBright bgCyanBright
white bgWhite whiteBright bgWhiteBright

Color naming in libraries: gray vs grey vs blackBright

The same ANSI codes 90 (gray) and 100 (bgGray) are named differently in various libraries.

Library Standard
gray
bgGray
UK spelling
grey
bgGrey
Spec-style
 blackBright
bgBlackBright
ansis
yoctocolors
kolorist
colors.js
picocolors
tinyrainbow
colorette
chalk
ansi-colors
kleur (8 colors) -
cli-color
colors-cli

Ansis prefers the more intuitive and commonly used names gray and bgGray, avoiding redundant aliases.

ANSI 256 colors

256 color functions:

  • Foreground: fg(code) - equivalent to chalk.ansi256(code)
  • Background: bg(code) - equivalent to chalk.bgAnsi256(code)

256 color codes:

See ANSI color codes.

Fallback

If a terminal supports only 16 colors then ANSI 256 colors will be interpolated into base 16 colors.

Usage example

import { bold, fg, bg } from 'ansis';

// foreground color
fg(96)`Bright Cyan`;

// background color
bg(105)`Bright Magenta`;

// function is chainable
fg(96).bold`bold Bright Cyan`;

// function is avaliable in each style
bold.fg(96).underline`bold underline Bright Cyan`;

// you can combine the functions and styles in any order
bg(105).fg(96)`cyan text on magenta background`

Truecolor

You can use the hex or rgb format.

Foreground function: hex() rgb()\ Background function: bgHex() bgRgb()

import { bold, hex, rgb, bgHex, bgRgb } from 'ansis';

// foreground color
hex('#E0115F').bold`bold Ruby`;
hex('#96C')`Amethyst`;
rgb(224, 17, 95).italic`italic Ruby`;

// background color
bgHex('#E0115F')`Ruby`;
bgHex('#96C')`Amethyst`;
bgRgb(224, 17, 95)`Ruby`;

// you can combine the functions and styles in any order
bold.hex('#E0115F').bgHex('#96C')`ruby bold text on amethyst background`

↑ top

Fallback

The ansis supports fallback to supported color level.

Truecolor —> 256 colors —> 16 colors —> no colors (black & white)

If you use the hex(), rgb() or ansis256() functions in a terminal not supported Truecolor or 256 colors, then colors will be interpolated.

output

↑ top

Extend with Custom Colors

By default, the imported ansis instance includes a set of base styles and standard ANSI colors. Define additional named colors using Truecolor hex code with the extend() method. Assign the result of extend() to a new variable (avoid reassigning the original instance).

[!TIP] Need help picking a color name? Try the Name that Color website - just enter a hex code.

Example:

import { Ansis } from 'ansis';

const myTheme = {
  orange: '#FFAB40',
  pink: '#FF75D1',
};

// Create an instance with extended colors
const ansis = new Ansis().extend(myTheme);

// Destructure extended and base colors
const { orange, pink, red } = ansis;

console.log(ansis.orange.bold('orange bold'));
console.log(orange.italic`orange italic`);
console.log(pink`pink color`);

TypeScript example:

import ansis, { AnsiColors } from 'ansis';

// Extends the built-in `AnsiColors` type with custom user defined color names.
type AnsiColorsExtend<T extends string> = AnsiColors | (T & Record<never, never>);

const myTheme = {
  orange: '#FFAB40',
  pink: '#FF75D1',
};

// Extend ansis with custom colors
const colors = ansis.extend(myTheme);

// Custom logger supporting both built-in and extended styles
const log = (style: AnsiColorsExtend<keyof typeof myTheme>, message: string) => {
  console.log(colors[style](message));
}

log('red', 'message'); // ✅ base color OK
log('orange', 'message'); // ✅ extended color OK
log('unknown', 'message'); // ❌ TypeScript Error

[!WARNING]

Extended colors must be used as the first item in the style chain:

colors.orange.bold('orange bold'); // ✅ works as expected
colors.bold.orange('bold orange'); // ❌ won't work: extended color used as a subchain

↑ top

CLI environment variables

By default, output in the terminal console is colored, while output in a file is uncolored.

To force enable or disable colored output, you can use the NO_COLOR and FORCE_COLOR environment variables.

NO_COLOR

Setting the NO_COLOR variable to any non-empty value will disable color output. For example:

NO_COLOR=1      # Disable colors
NO_COLOR=true   # Disable colors

Refer to the NO_COLOR standard for more details.

FORCE_COLOR

The FORCE_COLOR standard variable is used to control the color output in the terminal. The behavior of FORCE_COLOR in Ansis follows the Node.js convention, with a few adaptations:

Value Description
FORCE_COLOR=false Disables colors
FORCE_COLOR=0 Disables colors
FORCE_COLOR=true Auto-detects supported colors; enforces truecolor if none detected
FORCE_COLOR=(unset) Auto-detects supported colors; enforces truecolor if none detected
FORCE_COLOR=1 Enables 16 colors
FORCE_COLOR=2 Enables 256 colors
FORCE_COLOR=3 Enables truecolor

[!IMPORTANT] In Node.js FORCE_COLOR values of 1, true, and and an empty string ('') are treated as enabling 16 colors.

In Ansis:

  • 1 - enables exactly 16 colors
  • true - and an empty string trigger automatic color detection (16, 256, or truecolor).\ If no colors are detected, truecolor is enforced.

See:

For example, app.js:

import { red } from 'ansis';

console.log(red`red color`);

You can test the following behaviors by executing the script in the terminal:

node app.js           # Colored output in terminal
node app.js > log.txt # Output in file without ANSI codes

NO_COLOR=1 node app.js              # Force disable colors
FORCE_COLOR=0 node app.js           # Force disable colors
FORCE_COLOR=1 node app.js > log.txt # Force enable 16 colors
FORCE_COLOR=2 node app.js > log.txt # Force enable 256 colors
FORCE_COLOR=3 node app.js > log.txt # Force enable truecolor

COLORTERM

The COLORTERM environment variable indicates color support in terminal emulators. Its value depends on the terminal and its level of color support. Common values supported by Ansis are:

  • truecolor or 24bit - 16 million colors
  • ansi256 - 256 colors
  • ansi - 16 colors

To force a specific color level, you can set the COLORTERM variable before running the Node script:

COLORTERM=ansi      node script.js  # Force enable 16 colors
COLORTERM=ansi256   node script.js  # Force enable 256 colors
COLORTERM=truecolor node script.js  # Force enable truecolor

↑ top

Color levels

Ansis automatically detects color support, but you can manually set the color level.

Level Description
0 No colors (all colors disabled)
1 Basic colors (16 colors)
2 256 colors
3 Truecolor (16 million colors)

You can create a new instance of Ansis with the desired color level.

Disable colors:

import { Ansis } from 'ansis';

const custom = new Ansis(0);
console.log(custom.red`foo`); // Output: plain string, no ANSI codes

Use only basic colors:

import { Ansis } from 'ansis';

const custom = new Ansis(1);
console.log(custom.hex('#FFAB40')`Orange`); // Output: fallback to yellowBright

↑ top

Testing CLI output

Ansis automatically detects the supported color level (none, 16, 256, or truecolor) based on the environment.

To ensure consistent test results across different terminals and environments, you can explicitly set the desired color level using one of the supported environment variables: NO_COLOR, FORCE_COLOR or COLORTERM.

[!IMPORTANT]

You must define the environment variable before importing ansis.

process.env.NO_COLOR = '1'; // ❌ Doesn't work
import { red } from 'ansis'; // <- Too late! NO_COLOR is undefined when ansis loaded

Instead, create a separate file to set the environment variable and import it first:

import './no-color.js';       // ✅ Sets env variable early
import { red } from 'ansis';  // NO_COLOR is defined

Disable colors in tests

To ensure consistent test output without ANSI codes, you can disable color rendering using the NO_COLOR environment variable.

Disable via Environment Variable

Create a file: no-color.js:

process.env.NO_COLOR = '1';

Import this file first in your test:

import './no-color.js'; // disables colors
import { expect, test } from 'vitest';
import { red } from 'ansis';

console.log(red('foo')); // Output: plain "foo", no ANSI codes

test('output should not contain ANSI codes', () => {
  const output = red('foo');
  expect(output).toBe('foo');
});

Strip ANSI Codes with ansis.strip()

Alternatively, use ansis.strip() to remove color codes from strings in your tests:

import { expect, describe, test } from 'vitest';
import ansis, { red } from 'ansis';

test('should remove ANSI codes from output', () => {
  const output = red('foo');
  expect(ansis.strip(output)).toBe('foo');
});

Force truecolor

File: enable-truecolor.js:

process.env.COLORTERM = 'truecolor';

Test file:

import './enable-truecolor.js'; // enables truecolor
import { red, fg, hex } from 'ansis';

console.log(hex('#FFAB40')('orange')); // uses native ANSI RGB
console.log(fg(200)('pink'));          // uses ANSI 256
console.log(red('red'));               // uses ANSI 16

Force 256 colors

File: enable-256colors.js:

process.env.COLORTERM = 'ansi256';

Test file:

import './enable-256colors.js'; // enables 256 colors
import { red, fg, hex } from 'ansis';

console.log(hex('#FFAB40')('orange')); // fallback to ANSI 256 colors
console.log(fg(200)('pink'));          // uses ANSI 256 colors
console.log(red('red'));               // uses ANSI 16 colors

Force 16 colors

File: enable-16colors.js:

process.env.COLORTERM = 'ansi';

Test file:

import './enable-16colors.js'; // enables 16 colors
import { red, fg, hex } from 'ansis';

console.log(hex('#FFAB40')('orange')); // fallback to ANSI 16 colors (e.g., bright red)
console.log(fg(200)('pink'));          // fallback to ANSI 16 colors (e.g., bright magenta)
console.log(red('red'));               // uses ANSI 16 colors

↑ top

CLI arguments

Use cmd arguments --no-color to disable colors and --color to enable ones.

For example, an executable script app.js:

#!/usr/bin/env node
import { red } from 'ansis';

console.log(red`text`);

Execute the script in a terminal:

./app.js                        # colored output in terminal
./app.js --no-color             # non colored output in terminal

./app.js > log.txt              # output in file without ANSI codes
./app.js --color > log.txt      # output in file with ANSI codes

[!NOTE]

Command-line arguments take precedence over environment variables.


↑ top

Color support

Ansis automatically detects the supported color level:

  • Truecolor
  • ANSI 256 colors
  • ANSI 16 colors
  • black & white (no colors)

Ansis has the method isSupported() that returns a boolean value whether the output supports ANSI color and styles.

import ansis from 'ansis';

console.log('Color output: ', ansis.isSupported());

There is no standard way to detect terminal color support. The most common method is to check the TERM and COLORTERM environment variables, which often indicate the supported color level.

Most standard CI systems can be identified by the presence of the CI environment variable. While some CI uses their own specific environment variables, they are inconsistent and not widely adopted.

Ansis provides basic support for standard CI environments by checking the commonly used CI environment variable. In such cases, Ansis assumes support for at least 16 colors. If your code uses 256-color or truecolor, Ansis automatically fallback to 16 colors, or to black and white if no color support is detected.

Ansis explicitly detects GitHub Actions as supporting truecolor, as most Ansis users rely on GitHub CI.

Combined with information about the operating system, this approach provides a practical and lightweight method for detecting color support in most environments.

Terminal ANSI 16
colors
ANSI 256
colors
True
Color
env.
TERM
env.
COLORTERM
Specifically ENV variables
Azure CI dumb TF_BUILD
AGENT_NAME
GitHub CI dumb CI, GITHUB_ACTIONS
GitTea CI dumb CI, GITEA_ACTIONS
GitLab CI dumb CI, GITLAB_CI
Travis CI dumb TRAVIS
PM2
not isTTY
✅[^1] ✅[^1] ✅[^1] dumb PM2_HOME
pm_id
JetBrains TeamCity
>=2020.1.1
TEAMCITY_VERSION
JetBrains IDEA xterm-256color TERMINAL_EMULATOR='JetBrains-JediTerm'
VS Code xterm-256color truecolor
Windows
Terminal
✅[^2]
Windows
PowerShell
✅[^2]
macOS Terminal xterm-256color
iTerm xterm-256color truecolor
Kitty xterm-kitty truecolor
KDE Konsole xterm-256color truecolor

[^1]: Colors supported depends on actual terminal.\ [^2]: The Windows terminal supports true color since Windows 10 revision 14931 (2016-09-21).

See also:


↑ top

Compare the features of most popular libraries

Run the command to see the support of some features by various libraries:

npm run compare

Open in StackBlitz

Library Colors support Features
<nobr>- ESM | CJS</nobr>
<nobr> - named import</nobr>
<nobr>- naming colors</nobr>
<nobr>16 | 256 | 16m | 🌐</nobr> Fallback Chained
syntax
Nested
template
strings
${}
LF
\n
Supports
ENV vars
CLI flags
ansis
ESM CJS
<nobr>✅ named import</nobr>
✅ standard
✅ ✅ ✅ ✅ →256
→16
→b&w
NO_COLOR
FORCE_COLOR
COLORTERM
--no-color
--color
chalk v5
ESM
<nobr>❌ named import</nobr>
✅ standard
✅ ✅ ✅ ✅ →256
→16
→b&w
NO_COLOR
FORCE_COLOR
--no-color
--color
kolorist
ESM CJS
<nobr>✅ named import</nobr>
❌ standard
✅ ✅ ✅ ❌ →256
→b&w
NO_COLOR
FORCE_COLOR
cli-color
CJS
<nobr>❌ named import</nobr>
✅ standard
✅ ✅ ❌ 🛑 →16
→b&w
NO_COLOR
colors-cli
CJS
<nobr>❌ named import</nobr>
❌ standard
✅ ✅ ❌ 🛑 →b&w --no-color
--color
colors.js
CJS
<nobr>❌ named import</nobr>
❌ standard
✅ ❌ ❌ 🛑 →b&w FORCE_COLOR
--no-color
--color
ansi-colors
CJS
<nobr>❌ named import</nobr>
✅ standard
✅ ❌ ❌ ❌ FORCE_COLOR
colorette
ESM CJS
<nobr>✅ named import</nobr>
✅ standard
✅ ❌ ❌ 🛑 →b&w NO_COLOR
FORCE_COLOR
--no-color
--color
picocolors
CJS
<nobr>❌ named import</nobr>
✅ standard
✅ ❌ ❌ ❌ →b&w NO_COLOR
FORCE_COLOR
--no-color
--color
tinyrainbow
ESM
<nobr>❌ named import</nobr>
✅ standard
✅ ❌ ❌ ✅ →b&w NO_COLOR
FORCE_COLOR
FORCE_TTY
--no-color
--color
kleur
ESM CJS
<nobr>✅ named import</nobr>
✅ standard
❌ ❌ ❌ ✅
8 colors
→b&w NO_COLOR
FORCE_COLOR

Notes

Named import\ ESM\ import { red, green, blue } from 'lib';\ CJS\ const { red, green, blue } = require('lib');

Naming colors

  • standard: colors have standard names, e.g.: red, redBright, bgRed, bgRedBright
  • non-standard: colors have lib-specific names, e.g.: brightRed, bgBrightRed, red_b, red_btt

Colors support

  • 16 - ANSI 16 colors like red, redBright, bgRed, bgRedBright

  • 256 - ANSI 256 colors methods, e.g.:

  • 16m - Truecolor methods, e.g.: hex(), bgHex(), rgb(), bgRgb()

  • 🌐 - Colored output in Chromium-based browser console:

    • ✅ - colored output
    • ❌ - b&w output
    • 🛑 - fatal error by compilation or in runtime
  • Fallback - Truecolor → 256 colors → 16 colors → no colors

Features

  • Chained syntax\ lib.red.bold('text')

  • Nested template strings\ lib.red`text ${lib.cyan`nested`} text`

  • LF - Correct break styles at end-of-line (\n).

    console.log(bgGreen('\nAnsis\nNew Line\nNext New Line\n'))
    

    Outputs:\ output

Edge cases: input arguments

Compare how different libraries handle various input arguments in their functions.

Library c.reset() c.red() c.red(undefined) c.red(null) c.red('')
ansis \e[0m '' '' '' ''
chalk '' '' 'undefined' 'null' ''
picocolors undefined 'undefined' 'undefined' 'null' 'ESC'
tinyrainbow undefined 'undefined' 'undefined' 'null' 'ESC'
colorette '' '' '' 'null' ''
kleur [object] [object] [object] 'null' 'ESC'
ansi-colors '' '' '' '' ''
kolorist undefined 'undefined' 'undefined' 'null' 'ESC'
colors.js '' '' 'undefined' 'null' ''
cli-color - 'ESC' 'ESC' 'ESC' 'ESC'
colors-cli - Error 'undefined' 'null' 'ESC'

Legend:

  • '' - Returns an empty string without ANSI escape codes. This is the correct and expected behavior.
  • \e[0m - Returns the reset escape code.
  • 'ESC' - Returns an empty string containing ANSI escape codes, e.g., \e[31m\e[39m.
  • 'undefined' - Returns the styled string undefined.
  • 'null' - Returns the styled string null.
  • [object] - Returns an object of the library instance.
  • - - The feature is not supported.
  • Error - Causes a fatal error.

Other arguments are correctly handled by all libraries:

c.red(0)       // '0' in red
c.red(false)   // 'false' in red
c.red(true)    // 'true' in red
c.red(5/'1px') // 'NaN' in red
c.red(1/0)     // 'Infinity' in red

Ansis ensures consistent and predictable behavior for edge-case inputs, making it a reliable choice for usage.

↑ top

Compare the size of most popular packages

Package Dependencies Minified Unpacked Size Tarball size
ansis 0 uglified & minified 5.71 kB 3.4 kB
picocolors 0 no 6.37 kB 2.6 kB
tinyrainbow 0 uglified 8.1 kB 3.2 kB
colorette 0 no 17.0 kB 4.9 kB
kleur 0 no 20.3 kB 6.0 kB
ansi-colors 0 no 26.1 kB 8.5 kB
kolorist 0 no 51.0 kB 8.7 kB
colors.js 0 no 41.5 kB 11.1 kB
chalk 0 no 44.2 kB 13.4 kB
cli-color 5 no 754.0 kB 216.8 kB
colors-cli 0 no 511.0 kB 361.7 kB

Legend

  • Dependencies: Number of dependencies in the package.
  • Is Minified: Indicates whether the distributed npm package is minified.
  • Unpacked Size: The size of the npm package in the node_modules/ directory, (incl. dependencies).
  • Tarball size: The size of the downloaded *.tgz package file.\ You can check the package size with the following command:
    curl -s -o package.tgz $(npm view <package-name> dist.tarball) && echo "Tarball size: $(stat -f%z package.tgz | awk '{printf "%.2f", $1/1024}') kB"
    
    just replace the <package-name> with your package name.

See also:

  • npmjs - show install size of the published package, w/o dependencies
  • packagephobia - show total install size, incl. dependencies
  • npm download size - show download size
  • pkg-size - find the true size of an npm package
  • bundlephobia - useless, doesn't show real tarball size of the downloaded npm package

Show ANSI demo

git clone https://github.com/webdiscus/ansis.git
cd ./ansis
npm i
npm run demo

↑ top

Compatibility Check

Check the minimum version of your tool required for compatibility with the latest Ansis.

Tool Version Compatibility Supports
Node.js v14+ ✅ Full support CJS, ESM
Deno v2.0+ ✅ Full support CJS, ESM
TypeScript/tsc v5.0+ ✅ Full support CJS, ESM
esbuild v0.8+ ✅ Full support CJS, ESM
swc v1.2+ ✅ Full support CJS, ESM, FAUX
tsup v4.0+ ✅ Full support CJS, ESM, FAUX
tsx v3.0+ ✅ Full support CJS, ESM
Rollup v2.0+ ✅ Full support CJS, ESM
Rolldown v1.0.0-beta.8+ ✅ Full support CJS, ESM
Vite v2.5+ ✅ Full support ESM
Turbo v1.0+ ✅ Full support CJS, ESM
Webpack v5.0+ ✅ Full support CJS, ESM

Supports:

  • CJS: CommonJS module support.
  • ESM: ECMAScript module support.
  • FAUX: Fake or non-standard approach to module resolution (seen in swc).

Browser Compatibility for ANSI Codes

Browser Version Colors Supported
Chrome v20+ TrueColor (16M)
Safari v10+ TrueColor (16M)
Edge v12+ TrueColor (16M)
Opera v12+ TrueColor (16M)
Brave v1.0+ TrueColor (16M)
Vivaldi v1.0+ TrueColor (16M)

[!WARNING] Firefox doesn't natively support ANSI codes in the developer console.

↑ top

Benchmarks

[!CAUTION] The benchmark results are meaningless numbers intended purely to promote the library and increase its popularity. All libraries are more than fast enough. These results only to show the effectiveness of micro-optimizations in the code, which does not impact on real-world usage.

Of course Picocolors will be a little bit faster in a micro-benchmark since it has less code and doesn't handles edge cases.

Taken from the comment by the creator of Chalk.

To measure performance is used benchmark.js.

[!WARNING]

Results of vitest benchmark are incorrect.

The vitest benchmark generate unreal results.\ For example, the results of the simple bench:

chalk.red('foo') -  7.000.000 ops/sec
ansis.red('foo') - 23.000.000 ops/sec (x3 faster is incorrect result)

The actual performance results of Chalk and Ansis in this test are very similar.

Run benchmarks

git clone https://github.com/webdiscus/ansis.git
cd ./ansis
npm i
npm run build
npm run bench

Tested on

MacBook Pro 16" M1 Max 64GB\ macOS Sequoia 15.1\ Node.js v22.11.0\ Terminal iTerm2 v3.5.0


[!IMPORTANT]

Each library uses the recommended fastest styling method to compare the absolute performance.

In real practice, no one would use the slowest method (such as nested calls) to style a string when the library provides a faster and a shorter chained method.

For example:

lib.red.bold.bgWhite(' ERROR ')           // ✅ faster, shorter, readable
lib.red(lib.bold(lib.bgWhite(' ERROR '))) // ❌ slower, longer, unreadable

Simple bench

The simple test uses only single style. Picocolors, Colorette and Kleur do not support chained syntax or correct style break (wenn used `\n` in a string), so they are the fastest in this simple use case. No function, no performance overhead.

ansis.red('foo')
chalk.red('foo')
picocolors.red('foo')
...
+  picocolors@1.1.1    109.212.939 ops/sec
   colorette@2.0.20    108.044.800 ops/sec
   kleur@4.1.5          87.800.739 ops/sec
-> ansis@3.5.0          60.606.043 ops/sec  -44.5%
-  chalk@5.3.0          55.702.479 ops/sec  -48.9%
   kolorist@1.8.0       37.069.069 ops/sec
   ansi-colors@4.1.3    14.364.378 ops/sec
   colors@1.4.0          7.060.583 ops/sec
   cli-color@2.0.4       2.753.751 ops/sec
   colors-cli@1.0.33       897.746 ops/sec

Using 2 styles

Using only 2 styles, picocolors is already a bit slower, because using the chained syntax is faster than nested calls.

ansis.red.bold('foo')
chalk.red.bold('foo')
picocolors.red(picocolors.bold('foo')) // chained syntax is not supported
...
+  ansis@3.5.0          60.468.181 ops/sec
-  picocolors@1.1.1     58.777.183 ops/sec    -2.8%
-  chalk@5.3.0          47.789.020 ops/sec   -21.5%
   colorette@2.0.20     33.387.988 ops/sec
   kolorist@1.8.0       13.420.047 ops/sec
   kleur@4.1.5           5.972.681 ops/sec
   ansi-colors@4.1.3     4.086.412 ops/sec
   colors@1.4.0          3.018.244 ops/sec
   cli-color@2.0.4       1.817.039 ops/sec
   colors-cli@1.0.33       695.601 ops/sec

Using 3 styles

Using 3 styles, picocolors is 2x slower than ansis.

ansis.red.bold.bgWhite('foo')
chalk.red.bold.bgWhite('foo')
picocolors.red(picocolors.bold(picocolors.bgWhite('foo'))) // chained syntax is not supported
...
+  ansis@3.5.0          59.463.640 ops/sec
-  chalk@5.3.0          42.166.783 ops/sec  -29.0%
-  picocolors@1.1.1     32.434.017 ops/sec  -45.5% (~2x slower than Ansis)
   colorette@2.0.20     13.008.117 ops/sec
   kolorist@1.8.0        5.608.244 ops/sec
   kleur@4.1.5           5.268.630 ops/sec
   ansi-colors@4.1.3     2.145.517 ops/sec
   colors@1.4.0          1.686.728 ops/sec
   cli-color@2.0.4       1.453.611 ops/sec
   colors-cli@1.0.33       590.467 ops/sec

Using 4 styles

In rare cases, when using 4 styles, picocolors becomes 3.4x slower than ansis.

ansis.red.bold.underline.bgWhite('foo')
chalk.red.bold.underline.bgWhite('foo')
picocolors.red(picocolors.bold(picocolors.underline(picocolors.bgWhite('foo')))) // chained syntax is not supported
...
+  ansis@3.5.0          59.104.535 ops/sec
-  chalk@5.3.0          36.147.547 ops/sec  -38.8%
-  picocolors@1.1.1     17.581.709 ops/sec  -70.2% (~3x slower than Ansis)
   colorette@2.0.20      7.981.171 ops/sec
   kleur@4.1.5           4.825.665 ops/sec
   kolorist@1.8.0        3.729.880 ops/sec
   ansi-colors@4.1.3     1.514.053 ops/sec
   colors@1.4.0          1.229.999 ops/sec
   cli-color@2.0.4       1.210.931 ops/sec
   colors-cli@1.0.33       481.073 ops/sec

Deeply nested styles

The complex test with deeply nested single styles.

c.green(
  `green ${c.cyan(
    `cyan ${c.red(
      `red ${c.yellow(
        `yellow ${c.blue(
          `blue ${c.magenta(`magenta ${c.underline(`underline ${c.italic(`italic`)} underline`)} magenta`)} blue`,
        )} yellow`,
      )} red`,
    )} cyan`,
  )} green`,
)
+  colorette@2.0.20      1.110.056 ops/sec
-  picocolors@1.1.1      1.073.299 ops/sec
-> ansis@3.5.0             847.246 ops/sec  -23.7%
   kolorist@1.8.0          847.110 ops/sec
-  chalk@5.3.0             573.942 ops/sec  -48.3%
   kleur@4.1.5             471.285 ops/sec
   colors@1.4.0            439.588 ops/sec
   ansi-colors@4.1.3       382.862 ops/sec
   cli-color@2.0.4         213.351 ops/sec
   colors-cli@1.0.33        41.097 ops/sec

Colorette bench

The benchmark used in colorette for single styles.

c.red(`${c.bold(`${c.cyan(`${c.yellow('yellow')}cyan`)}`)}red`)
+  picocolors@1.1.1      3.861.384 ops/sec
   colorette@2.0.20      3.815.039 ops/sec
-> ansis@3.5.0           2.918.269 ops/sec  -24.4%
   kolorist@1.8.0        2.548.564 ops/sec
-  chalk@5.3.0           2.502.850 ops/sec  -35.2%
   kleur@4.1.5           2.229.023 ops/sec
   ansi-colors@4.1.3     1.426.279 ops/sec
   colors@1.4.0          1.123.139 ops/sec
   cli-color@2.0.4         481.708 ops/sec
   colors-cli@1.0.33       114.570 ops/sec

Picocolors complex bench

The picocolors benchmark, slightly modified. Added a bit more complexity by applying two styles to the colored word instead of one.

let index = 1e8;
c.red('.') +
c.yellow('.') +
c.green('.') +
c.red.bold(' ERROR ') +
c.red('Add plugin ' + c.cyan.underline('name') + ' to use time limit with ' + c.cyan(++index));
+  picocolors@1.1.1      2.601.559 ops/sec
-> ansis@3.5.0           2.501.227 ops/sec   -3.8%
   colorette@2.0.20      2.326.491 ops/sec
-  chalk@5.3.0           2.129.106 ops/sec  -18.1%
   kleur@4.1.5           1.780.496 ops/sec
   kolorist@1.8.0        1.685.703 ops/sec
   ansi-colors@4.1.3       838.542 ops/sec
   colors@1.4.0            533.362 ops/sec
   cli-color@2.0.4         287.558 ops/sec
   colors-cli@1.0.33        97.463 ops/sec

[!NOTE]

In this test, which is closer to practical use, each library uses the fastest styling method available.

So, chalk, ansis, ansi-colors, cli-color, colors-cli and colors uses chained method, e.g. c.red.bold(' ERROR '). While picocolors, colorette and kolorist uses nested calls, e.g. c.red(c.bold(' ERROR ')), because doesn't support the chained syntax.


↑ top

How to switch to Ansis

Ansis is a powerful, small, and fast replacement for many similar libraries.\ Just replace your import ... from ... or require(...) to ansis.

Migrating from chalk

- import chalk from 'chalk';
+ import chalk from 'ansis';

Ansis supports the Chalk syntax and is compatible* with styles and color names, so you don't need to modify the original code:

chalk.red.bold('Error!');

// colorize "Error: file not found!"
chalk.red(`Error: ${chalk.cyan.bold('file')} not found!`);

// truecolor
chalk.hex('#FFA500').bold('Bold orange color');
chalk.rgb(123, 45, 67).underline('Underlined reddish color');
chalk.bgHex('#E0115F')('Ruby');
chalk.bgHex('#96C')('Amethyst');

[!WARNING]

If used ANSI 256 colors functions, replace them with Ansis equivalents:

- chalk.ansi256(196)('Error');
+ ansis.fg((196)('Error');

- chalk.bgAnsi256(21)('Info');
+ ansis.bg(21)('Info');

[!WARNING]

Ansis doesn't not support the overline style, because it's not widely supported and no one uses it.\ Check you code and remove the overline style:

- chalk.red.overline('text');
+ chalk.red('text');

Optionally, you can rewrite the same code to make it even shorter and cleaner:

import { red, cyan, fg, bg, hex, rgb, bgHex, bgRgb } from 'ansis';

red.bold('Error!'); // using parentheses
red.bold`Error!`;   // using template string

// colorize "Error: file not found!"
red`Error: ${cyan.bold`file`} not found!`;

// ANSI 256 colors
fg(93)`Violet color`; // equivalent for chalk.ansi256()
bg(194)`Honeydew, more or less`;  // equivalent for chalk.bgAnsi256()

// truecolor
hex('#FFA500').bold`Bold orange color`;
rgb(123, 45, 67).underline`Underlined reddish color`;
bgHex('#E0115F')`Ruby`;
bgHex('#96C')`Amethyst`;

↑ top

Migrating from colorette

- import { red, bold, underline } from 'colorette';
+ import { red, bold, underline } from 'ansis';

Ansis is fully compatible with colorette styles and color names, so you don't need to modify the original code:

red.bold('Error!');
bold(`I'm ${red(`da ba ${underline("dee")} da ba`)} daa`);

Optionally, you can rewrite the same code to make it even shorter and cleaner:

red.bold`Error!`;
bold`I'm ${red`da ba ${underline`dee`} da ba`} daa`;

↑ top

Migrating from picocolors

- import pico from 'picocolors';
+ import pico from 'ansis';

Ansis is fully compatible with picocolors styles and color names, so you don't need to modify the original code:

pico.red(pico.bold('text'));
pico.red(pico.bold(variable));

// colorize "Error: file not found!"
pico.red('Error: ' + pico.cyan(pico.bold('file')) + ' not found!');

Optionally, you can rewrite the same code to make it even shorter and cleaner:

import { red, cyan } from 'ansis';

red.bold`text`;
red.bold(variable);

// colorize "Error: file not found!"
red`Error: ${cyan.bold`file`} not found!`

↑ top

Migrating from ansi-colors

- const c = require('ansi-colors');
+ const c = require('ansis');

Ansis is fully compatible with ansi-color styles and color names, so you don't need to modify the original code:

c.red.bold('Error!');

// colorize "Error: file not found!"
c.red(`Error: ${c.cyan.bold('file')} not found!`);

Optionally, you can rewrite the same code to make it even shorter and cleaner:

import { red, cyan } from 'ansis';

red.bold('Error!'); // using parentheses
red.bold`Error!`;   // using template string

// colorize "Error: file not found!"
red`Error: ${cyan.bold`file`} not found!`;

↑ top

Migrating from kleur

- import { red, green, yellow, cyan } from 'kleur';
+ import { red, green, yellow, cyan } from 'ansis';

Ansis is fully compatible with kleur styles and color names, but Kleur v3.0 no longer uses Chalk-style syntax (magical getter):

green().bold().underline('this is a bold green underlined message');
yellow(`foo ${red().bold('red')} bar ${cyan('cyan')} baz`);

If you uses chained methods then it requires a simple code modification. Just replace (). with .:

green.bold.underline('this is a bold green underlined message');
yellow(`foo ${red.bold('red')} bar ${cyan('cyan')} baz`);

Optionally, you can rewrite the same code to make it even shorter and cleaner:

yellow`foo ${red.bold`red`} bar ${cyan`cyan`} baz`;

↑ top

Migrating from cli-color

- const clc = require('cli-color');
+ const clc = require('ansis');

Ansis is compatible* with cli-color styles and color names:

clc.red.bold('Error!');

// colorize "Error: file not found!"
clc.red(`Error: ${c.cyan.bold('file')} not found!`);

[!WARNING]

Ansis doesn't not support the blink style, because it's not widely supported and no one uses it.\ Check you code and remove the blink style:

- clc.red.blink('text');
+ clc.red('text');

If you use ANSI 256 color functions, replace xterm with fg and bgXterm replace bg:

- clc.xterm(202).bgXterm(236)('Orange text on dark gray background');
+ clc.fg(202).bg(236)('Orange text on dark gray background');

Optionally, you can rewrite the same code to make it even shorter and cleaner:

import { red, cyan, fg, bg } from 'ansis';

red.bold`Error!`;

// colorize "Error: file not found!"
red`Error: ${cyan.bold`file`} not found!`;

fg(202).bg(236)`Orange text on dark gray background`;

↑ top

Testing

npm run test will run the unit and integration tests.\ npm run test:coverage will run the tests with coverage.


↑ top

License

ISC

更新日志

Changelog

Pre release note: ✨ Ansis v4 - Smaller package, and cleaner API

Ansis v4 drops legacy baggage and unused artifacts. This release brings a stable and more compact ANSI library. v4.0.0 is 12.4% smaller than v3.17.0.

4.0.0-beta.21 (2025-04-24)

⚠️ BREAKING CHANGE

  • feat: drop support for Deno 1.x (EOL - 9 Oct 2024) and add support for Deno 2.0+, #37 Backported from 3.18.0-beta.0

4.0.0-beta.20 (2025-04-21)

⚠️ BREAKING CHANGE

Removed unused and rarely used aliases for gray and bgGray:

  • grey, bgGrey - British spelling, uncommon, redundant aliases for gray and bgGray
  • blackBright, bgBlackBright - Spec-style names for "bright black", less intuitive, rarely used, and awkward in practice

Supporting three separate names for the same color is too much and introduces ambiguity into the API.

Migrating

Replace deprecated aliases with the preferred standard names:

- ansis.grey('text')
- ansis.blackBright('text')
+ ansis.gray('text')

- ansis.bgGrey('text')
- ansis.bgBlackBright('text')
+ ansis.bgGray('text')

4.0.0-beta.19 (2025-04-20)

⚠️ BREAKING CHANGE

The unused AnsiColorsExtend type has been removed.

This type was intended to support extended theme colors, but it was never used in other projects. If you relied on it in your own code (e.g. for typing custom styles), you can easily define it yourself.

Migrating

If you previously used the AnsiColorsExtend type, you’ll now need to define a custom utility type. Here's an example how to update your code:

- import ansis, { AnsiColorsExtend } from 'ansis';
+ import ansis, { AnsiColors } from 'ansis';

+ type AnsiColorsExtend<T extends string> = AnsiColors | (T & Record<never, never>);

const myTheme = {
  orange: '#FFAB40',
};

// Extend ansis with custom colors
const colors = ansis.extend(myTheme);

// Custom logger supporting both built-in and extended styles
const log = (style: AnsiColorsExtend<keyof typeof myTheme>, message: string) => {
  console.log(colors[style](message));
}

log('orange', 'message'); // extended color

This change ensures compatibility with the latest version of Ansis, where AnsiColorsExtend is no longer available.

4.0.0-beta.18 (2025-04-18)

⚠️ BREAKING CHANGE (if using 256-color functions)

The following legacy method aliases have been removed:

❌ Removed Method ✅ Use Instead
ansi256(code) fg(code)
bgAnsi256(code) bg(code)

These aliases were originally added for compatibility with Chalk. Starting with this release, Ansis focuses on a cleaner and compact API, free from duplicated methods and legacy layers.

Why fg() and bg() are better than ansi256() and bgAnsi256()

Ansis has grown beyond being a Chalk-compatible alternative - it's now a modern and compact ANSI library with its own identity.

Clear and expressive API

  • ansis.fg(code) and ansis.bg(code) are shorter more elegant than ansis.ansi256(code) and ansis.bgAnsi256(code)
  • fg and bg clearly describe their purpose: setting foreground and background colors
  • These method names align with conventions used by many other color libraries
  • Introduced in 2021-12-29, fg() and bg() are already being used in GitHub projects
  • Removing duplicates makes the API cleaner and more compact

Migrating

Updating from a previous version is simple:

import ansis from 'ansis';

- ansis.ansi256(196)('Error')
+ ansis.fg(196)('Error')

- ansis.bgAnsi256(21)('Info')
+ ansis.bg(21)('Info')

Alternatively, to keep compatibility with existing code:

- import { ansi256, bgAnsi256 } from 'ansis';
+ import { fg as ansi256, bg as bgAnsi256 } from 'ansis';

ansi256(196)('Error')
bgAnsi256(21)('Info')

No other changes are required - everything else remains fully compatible.

4.0.0-beta.17 (2025-04-18)

  • feat: refactor .d.ts and reduce the package size

4.0.0-beta.16 (2025-04-16)

⚠️ BREAKING CHANGE: Improved extend() method

The extend() method has been redesigned for better TypeScript support and flexibility.

Old behavior:

extend<U extends string>(colors: Record<U, string | P>): asserts this is Ansis & Record<U, Ansis>;
  • Modifies the current instance in-place.
  • Returns void.
  • ✅ Worked with default instance:

    import ansis from 'ansis';
    
    ansis.extend({ pink: '#FF75D1' });
    console.log(ansis.pink('foo'));
    
  • Limitation - Did not work with newly created instances:

    import { Ansis } from 'ansis';
    
    const ansis = new Ansis();
    ansis.extend({ pink: '#FF75D1' });
    console.log(ansis.pink('Hello')); // TS2339: Property 'pink' does not exist
    

New behavior:

extend<U extends string>(colors: Record<U, string | P>): Ansis & Record<U, Ansis>;
  • Returns a new extended instance with full type support.
  • ✅ Works with both ansis and new Ansis():

    import ansis, { Ansis } from 'ansis';
    
    const colors = ansis.extend({ pink: '#FF75D1' });
    console.log(colors.pink('foo'));
    
    const custom = new Ansis().extend({ apple: '#4FA83D' });
    console.log(custom.apple('bar'));
    

Why this change?

TypeScript cannot widen the type of an existing variable when using asserts. This means the old approach only worked for top-level constants like ansis, not new instances. By returning the extended instance, the new approach enables full type inference in all scenarios.

Summary:

  • asserts version removed
  • extend() now returns a new instance with extended types
  • Cleaner, safer, and fully compatible with all usage patterns

Migrating

The new extend() method now returns an extended instance instead of modifying the original in-place. To migrate, assign the result of extend() to a new variable (avoid reassigning the original instance):

import ansis from 'ansis';

- ansis.extend({ pink: '#FF75D1' });
+ const theme = ansis.extend({ pink: '#FF75D1' });

- console.log(ansis.pink('foo'));
+ console.log(theme.pink('foo'));

Or

import { Ansis } from 'ansis';

- ansis.extend({ pink: '#FF75D1' });
+ const ansis = new Ansis().extend({ pink: '#FF75D1' });

console.log(ansis.pink('foo'));

Features

Manually set the color level

Ansis automatically detects color support, but you can manually set the color level. You can create a new instance of Ansis with the desired color level.

Disable colors:

import { Ansis } from 'ansis';

const custom = new Ansis(0);
console.log(custom.red`foo`); // Output: plain string, no ANSI codes

Use only basic colors:

import { Ansis } from 'ansis';

const custom = new Ansis(1);
console.log(custom.hex('#FFAB40')`Orange`); // Output: fallback to yellowBright

4.0.0-beta.14 (2025-04-13)

  • feat: reduce size of index.d.ts file

4.0.0-beta.13 (2025-04-12)

  • feat: reduce the package size

4.0.0-beta.9 (2025-03-13)

  • feat: slightly improve performance for hex function

4.0.0-beta.4 (2025-03-08)

Features

Dropped xterm-direct terminfo check for truecolor support (not a breaking change)

The xterm-direct detection logic (introduced in v3.5.0) has been removed, as it's unnecessary for identifying truecolor-capable terminals.

Note

No terminal emulator sets TERM=xterm-direct by default. Modern terminals, including KDE Konsole, typically use TERM=xterm-256color along with COLORTERM=truecolor to indicate truecolor support.

4.0.0-beta.2 (2025-03-07)

Fixes

Defaults to 16 colors when terminal color support is unknown

Ansis now defaults uses 16 colors if it cannot detect support for 256 colors or truecolor.

  • Old behavior: Unknown terminal → used truecolor (could result in incorrect colors)
  • New behavior: Unknown terminal → uses only 16 colors (ensures broad compatibility)

Note

This is not a breaking change. Ansis gracefully interpolates higher color depths (truecolor and 256 colors) down to 16 colors when using fg(), hex() or rgb(). To explicitly enable truecolor, set the environment variable COLORTERM=24bit or FORCE_COLOR=3.

4.0.0-beta.1 (2025-03-03)

BREAKING CHANGE (very unlikely impact): Removed non-standard strike style (alias for strikethrough)

The legacy strike alias has been removed to clean up the API and stay consistent with ANSI style conventions.

  • The strike style was rarely (if ever) used and added unnecessary redundancy.
  • No usage of ansis.strike() was found in public GitHub repositories.
  • Other ANSI libraries use the standard strikethrough name exclusively.

Migrating

If you're using strike style, replace it with strikethrough.


Features

Support escape sequences in tagged template literals

Ansis now treats tagged template literals the same way as normal strings, returning the same result as the standard function call.

Example with \n (newline, unescaped):

red('prev\nnext')
red`prev\nnext`

Output:

prev
next

Example with escaped backslash:

red('prev\\next')
red`prev\\next`

Output:

prev\next

4.0.0-beta.0 (2025-03-02)

Deprecated.


3.18.0-beta.0 (2025-04-22)

  • feat: drop support for Deno 1.x (EOL - 9 Oct 2024) and add support for Deno 2.0+, #37
  • test: add Deno tests on GitHub

3.17.0 (2025-03-02)

  • feat: add support for typescript < 5.6 to fix TS2526 error:
    A 'this' type is available only in a non-static member of a class or interface.
    
    NOTE: If you are already using TypeScript >= 5.6, this update is not required.

3.16.0 (2025-02-21)

  • chore: after testing bump version to release version 3.16.0

3.16.0-beta.3 (2025-02-21)

3.16.0-beta.0 (2025-02-19)

  • refactor: micro optimisations for named exports to slight reduce the package size by ~40 bytes.

3.15.0 (2025-02-16)

  • feat: reduce the package size by ~200 bytes.
  • refactor: invisible micro optimisations.
  • chore: after testing in many projects bump v3.15.0-beta.2 to release v3.15.0.
  • chore: update dev dependencies.
  • test: add tests for tsup bundler.

3.15.0-beta.2 (2025-02-15)

  • refactor: slight reduce the package size

3.15.0-beta.1 (2025-02-15)

  • feat: remove "main" from package.json, since Ansis is a dual package using "exports".\ Note:
    • requires Node >= v12.7.0 to support "exports".
    • npm does not require "main" for publishing a package.
    • Node.js prioritizes "exports" over "main" when resolving modules.
    • Modern bundlers and tools (like Webpack, Rollup, and TypeScript) also use "exports".
  • docs: add to README the Compatibility Check for tools and browsers.

3.15.0-beta.0 (2025-02-14)

  • feat: reduce the package size by ~100 bytes
  • refactor: invisible micro optimisations

3.14.0 (2025-02-13)

  • feat: add support for chromium-based browsers.\ Now you can use truecolor in the consoles of Chrome, Edge, Brave, and other Chromium-based browsers. Browsers that do not support ANSI codes will display black and white text.
  • refactor: slight reduce the package size by ~40 bytes.

3.13.0 (2025-02-13)

Skip this version number.

3.12.0 (2025-02-11)

  • feat: add support for \n as a newline in template literals, e.g.: green`Hello\nWorld` renders:
    Hello
    World
    

3.11.0 (2025-02-09)

  • feat: add support for legacy Node.js v14 (in package.json for npm was changed the engines to "node": ">=14")
  • test: add test in GitHub workflow for legacy Node.js versions: 14, 16
  • chore: update dev dependencies

3.10.0 (2025-01-27)

  • feat: ansis.reset() returns the reset escape code \e[0m
  • feat: micro optimisations for slight performance improvements
  • chore: code cleanup
  • docs: update readme

3.9.1 (2025-01-15)

  • refactor: invisible code improvements
  • chore: add benchmark for long text
  • docs: improve readme

3.9.0 (2025-01-13)

  • feat: revert handling of null and undefined values to empty string as before v3.7.0, #25

3.8.1 (2025-01-10)

  • refactor: optimize package size

3.8.0 (2025-01-09)

  • feat: enforce a specific color support by a FORCE_COLOR value:

    • false - Disables colors
    • 0 - Disables colors
    • true (or unset) - Auto detects the supported colors (if no color detected, enforce truecolor)
    • 1 - Enables 16 colors
    • 2 - Enables 256 colors
    • 3 - Enables truecolor
  • fix: if the function argument is an empty string should be returned an empty string w/o escape codes:

    ansis.red('') => '', // returns empty string w/o escape codes
    
  • refactor: optimize code by size

3.7.0 (2025-01-07)

  • fix: cast falsy values false, null, undefined, NaN to a string. In previous versions, the empty string '' was returned for falsy values.
  • fix: functions with argument 0 , e.g. ansis.red(0), returning empty string '', now return colored value '0'
  • test: add tests for function arguments with various types

3.6.0 (2025-01-04)

  • feat: remove undocumented pointless dummy function ansis(any)

    [!WARNING] This is not a BREAKING CHANGE because it was never officially documented!

    import ansis from 'ansis';
    ansis('text'); // <= now will occur the ERROR TS2349: This expression is not callable.
    

    This warning applies only to projects where Chalk was replaced with Ansis and something like chalk('text') was used.

    Just replace ansis('text') with 'text'.

    The ansis('text') function was a dummy and did nothing except return the same input string.

  • chore: update license to current date

3.5.2 (2024-12-28)

  • fix: TS2339: Property 'strip' does not exist on type when the TS compiler option module is node16
  • refactor: optimize index.d.ts to reduce package size from 7.3 kB to 7.0 kB

3.5.1 (2024-12-26)

  • refactor: invisible code optimisation

3.5.0 (2024-12-26) release

  • refactor: optimise npm package to reduce size by 3 kB, from 10.3 kB to 7.3 kB
  • feat: add support the COLORTERM variable for values: truecolor, 24bit, ansi256, ansi (16 colors)
  • feat: add support the xterm-direct terminal to detect the truecolor
  • fix: remove detection environment variable GPG_TTY introduced in 3.5.0-beta.0 version, because it make no sense
  • fix: default import in TypeScript, compiled with tsc: import ansis from 'ansis' now works so well as import * as ansis from 'ansis'

3.5.0-beta.6 (2024-12-25)

  • refactor: optimise npm package to reduce the size
  • chore: update benchmarks with newest version
  • test: add more use cases

3.5.0-beta.5 (2024-12-24)

  • feat: detect xterm-direct terminal as supported the truecolor
  • feat: add support the COLORTERM variable for values: truecolor, 24bit, ansi256, ansi (16 colors)
  • docs: update readme for using COLORTERM with examples

3.5.0-beta.4 (2024-12-23)

  • docs: remove badges in readme for npm package to reduce package size

3.5.0-beta.3 (2024-12-23)

  • docs: fix badge urls in readme for npm package

3.5.0-beta.2 (2024-12-23)

  • refactor: optimise npm package to reduce the size by ~0.5 kB, from 8.0 kB to 7.5 kB
  • test: fix swc configuration for compiling into CJS
  • test: fix handling line endings on windows

3.5.0-beta.1 (2024-12-23)

  • refactor: optimise npm package to reduce the size by ~1 kB, from 8.9 kB to 8.0 kB

3.5.0-beta.0 (2024-12-21)

  • feat: add support environment variable GPG_TTY to detect it as isTTY. NOTE: in release v3.5.1 was removed as needles.
  • fix: default import in TypeScript, compiled with tsc: import ansis from 'ansis' now works so well as import * as ansis from 'ansis'
  • refactor: optimise npm package to reduce size by ~1.3 kB, from 10.3 kB to 8.9 kB
  • refactor: optimize index.d.ts, remove insignificant spaces and words, use the type with dynamic properties instead of the interface
  • test: add integration tests to execute compiled TypeScript and compare outputs with expected strings
  • test: add tests for tsc, swc and esbuild compilers

3.4.0 (2024-12-14)

  • refactor: optimise npm package to reduce size by ~1 KB, from 11.3 kB to 10.3 kB

3.4.0-beta.1 (2024-12-12)

  • fix: url to GitHub in readme for npm package

3.4.0-beta.0 (2024-12-12)

  • refactor: invisible code optimisations
  • refactor: optimize readme for npm package to save ~400 bytes
  • refactor: optimize index.d.ts for npm package to save ~500 bytes
  • test: refactor benchmark tests
  • test: add new representative benchmark tests for using 1, 2, 3 and 4 styles
  • test: add picocolors complex benchmark test
  • docs: update readme

3.3.2 (2024-07-23)

  • fix: correct detect TTY on Windows platform
  • chore: optimize code to reduce the size by ~50 bytes
  • chore: add benchmarks for kolorist package
  • test: add test matrix for windows on GitHub
  • docs: add compare the size of most popular packages

3.3.1 (2024-07-18)

  • chore: optimize code to reduce the size by ~600 bytes,
  • chore: minify index.d.ts to reduce the size by ~200 bytes,
  • chore: increase performance, e.g. using chained styles, 70.000.000 -> 80.000.000 ops/sec

3.3.0 (2024-07-14)

  • feat(BREAKING CHANGE): remove old named import DEPRECATED in v2.0.0 (2023-11-03). If you update the package from v1.x to v3.3.0 then check your code:\ ESM
    - import { red } from 'ansis/colors';
    + import { red } from 'ansis';
    
    CJS
    - const { red } = require('ansis/colors');
    + const { red } = require('ansis');
    
  • chore: cleanup/optimize package.json for npm package

3.2.1 (2024-07-12)

  • chore: reduce unpacked size by ~ 1 KB
  • docs: optimize README for NPM

3.2.0 (2024-04-24)

  • feat: add ansis.isSupported() method to detect color support

3.1.1 (2024-04-15)

  • fix: interpret FORCE_COLOR=false or FORCE_COLOR=0 as force disable colors\ others values, e.g., FORCE_COLOR=true or FORCE_COLOR=1 - force enable colors.\ See https://force-color.org.

3.1.0 (2024-04-10)

  • feat: add detection of color support when using PM2 process manager

3.0.3 (2024-04-09)

  • chore: add rollup-plugin-cleanup to remove comments from d.ts file for dist, that save yet 3 KB
  • chore: update license year

3.0.2 (2024-04-08)

  • chore: create mini version of README for NPM to minify package size
  • docs: update readme

3.0.1 (2024-04-01)

  • refactor: improve code
  • chore: reduce code bundle size from 3.8 KB to 3.4 KB
  • chore: update benchmark
  • chore: update compare tests
  • test: add more tests
  • docs: improve readme

3.0.0 (2024-03-29)

  • feat: add detection of color levels support: TrueColor, 256 colors, 16 colors, no color
  • feat: add fallback for supported color space: truecolor —> 256 colors —> 16 colors —> no colors
  • perform: improve performance for hex() function
  • chore: size increased from 3.2 KB to 3.8 KB as new features were added
  • test: switch from jest to vitest
  • test: add tests for new features
  • docs: update readme for color levels support

BREAKING CHANGE

In the new major version 3.x are removed unused styles and methods.

⚠️ Warning

Before update, please check your code whether is used deleted styles and methods.

Support Node.js

Drop supports for Node <= 14. Minimal supported version is 15.0.0 (Released 2020-10-20). In the theory the v3 can works with Node12, but we can't test it.

Deleted DEPRECATED named import syntax (since v3.3.0)

ESM

- import { red } from 'ansis/colors';
+ import { red } from 'ansis';

CJS

- const { red } = require('ansis/colors');
+ const { red } = require('ansis');

Deleted styles

The not widely supported styles are deleted:

  • faint (alias for dim), replace in your code with dim
  • doubleUnderline, replace in your code with underline
  • frame, replace in your code with underline
  • encircle, replace in your code with underline
  • overline, replace in your code with underline

Deleted methods

The methods are deleted:

  • ansi, replace in your code with fg
  • bgAnsi, replace in your code with bg

Deleted clamp in functions

The clamp (0, 255) for the ANSI 256 codes and RGB values is removed, because is unused. You should self check the function arguments.

The affected functions:

  • fg - expected a code in the range 0 - 255
  • bg - expected a code in the range0 - 255
  • rgb - expected r, g, b values in the range 0 - 255
  • bgRgb - expected r, g, b values in the range 0 - 255

2.3.0 (2024-02-15)

  • feat: add detection of additional terminals, thanks @dse, colors.js:issue #42
  • test: add test to detect various terminals

2.2.0 (2024-02-03)

  • feat: add supports the argument as number
  • test: add tests for new feature
  • chore: add features compare of different libs, just run: npm run compare
  • chore: add compare example on stackblitz
  • docs: update readme

2.1.0 (2024-01-30)

  • feat: add bgGrey and bgGray aliases for bgBlackBright
  • refactor: optimize source code
  • test: refactor tests
  • docs: update readme

2.0.3 (2023-12-14)

  • fix(index.d.ts): use function overload to make the tagged template have the correct type, #16

2.0.2 (2023-11-14)

  • fix: could not find a declaration file for module 'ansis'

2.0.1 (2023-11-03)

  • fix: missing exports of ansis.strip() and ansis.export() functions (issue was introduced in v2.0.0)
  • refactor: optimize code to reduce distributed size
  • test: add test for generated npm package in CJS and ESM mode
  • test: add test for env variables and CLI flags
  • test: add test to detect Deno
  • test: add test to detect Next.js runtime
  • docs: update readme

2.0.0 (2023-11-03)

  • feat: add supports the Deno
  • feat: add supports the Next.js edge runtime
  • feat(CHANGE): add named import for ansis:\ NEW named import: import { red } from 'ansis'.\ If you use TypeScript and your IDE show the error: TS2307: Cannot find module ansis/colors,\ then you should use the new syntax, update you code: import { red } from 'ansis/colors' --> import { red } from 'ansis'.
  • feat(DEPRECATE): OLD named import import { red } from 'ansis/colors' is deprecated, use the NEW named import
  • feat(DEPRECATE): instead of the ansi use fg
  • feat(DEPRECATE): instead of the bgAnsi use bg
  • feat: optimize named export
  • feat: reduce the size of dist/ directory
  • chore: update dev dependencies, new jest requires node.js >= 14

1.6.0-beta.0 (2023-11-01)

  • feat: add supports the Deno
  • feat: add supports the Next.js edge runtime
  • test: add tests for isSupported() function
  • chore: update dev dependencies

1.5.6 (2023-09-21)

  • chore: update dev dependencies
  • chore: add SECURITY.md
  • chore: add PULL_REQUEST_TEMPLATE.md
  • chore: update ISSUE_TEMPLATE
  • docs: update readme

1.5.5 (2022-09-22)

  • refactor: optimize code to reduce size by 120 bytes
  • test: add test for isSupported() function
  • docs: update readme, add example screenshots

1.5.4 (2022-09-14)

  • fix: visible style with nested template strings

1.5.3 (2022-09-14)

  • fix: set correct aliases for bgAnsi and fg methods by named export
  • chore: refactor examples
  • docs: update readme

1.5.2 (2022-09-10)

  • fix: regard the value of the environment variable FORCE_COLOR=0 to force disable colors
  • test: add tests for FORCE_COLOR
  • docs: update readme

1.5.1 (2022-09-08)

  • fix: add missing export for CJS mode in package.json
  • test: add manual tests for CJS and ESM mode

1.5.0 (2022-09-08)

  • DEPRECATE v1.5.0, because missing exports main for CJS mode, fixed in v1.5.1

1.5.0 (2022-09-08)

  • feat: add supports the nested template literal syntax:
    console.log(red`red ${yellow`yellow ${green`green`} yellow`} red`)
    
  • feat: add named export of colors with supports for chained syntax:
    import { red, green, yellow } from 'ansis/colors';
    console.log(red.bold.underline`text`);
    
  • feat: add extending of base colors with named custom truecolor
    import ansis from 'ansis';
    ansis.extend({ orange: '#FFAB40' });
    console.log(ansis.orange.bold('text'));
    
  • fix: corrected declarations in index.d.ts
  • chore: add AnsiStyles, AnsiColors and AnsiColorsExtend types in index.d.ts
  • refactor: optimize size of distributed bundle from 3.7KB to 3.1KB
  • docs: add usage in CLI

1.4.0 (2022-07-02)

  • feat: add method strip() to remove all ANSI codes from string

1.3.6 (2022-04-27)

  • build: properly generated distribution package, bump to last stable version 1.3.6
  • chore: update dev packages

1.3.5 (2022-04-27)

  • DEPRECATED: this version is broken

1.3.4 (2022-01-30)

  • feat: optimize distributed code size to smaller than 4 KB

1.3.3 (2022-01-24)

  • feat: add UK spelling alias grey for gray
  • chore: update dev dependencies
  • docs: update readme

1.3.2 (2021-12-30)

  • feat: add bundle generation for ESM
  • build: auto generate bundles for ESM and CommonJS at npm publish

1.3.1 (2021-12-29)

  • fix: usage for CommonJS: const ansis = require('ansis').default; --> const ansis = require('ansis');

1.3.0 (2021-12-29)

  • feat: add support CommonJS (now supported ESM and CommonJS)
  • feat: add aliases: .fg() for .ansi256() and .bg() for .bgAnsi256() methods. DEPRECATED methods: ansi, ansi256, bgAnsi,bgAnsi256 - use fg and bg instead.
  • fix: some inner param types
  • chore: remove examples from NPM package (it can be cloned und run local)

1.2.2 (2021-12-28)

  • fix: the path of examples in package.json

1.2.1 (2021-12-28)

  • chore: add demo examples of all features
  • docs: update readme

1.2.0 (2021-12-27)

  • feat: add supports the environment variables NO_COLOR FORCE_COLOR and flags --no-color --color
  • feat: add aliases ansi for ansi256 and bgAnsi for bgAnsi256
  • docs: add to readme the compare of most popular ANSI libraries

1.1.1 (2021-12-27)

  • feat: add the class Ansis to create more independent instances to increase the performance by benchmark
  • feat: improve performance
  • refactor: code refactoring
  • docs: update readme

1.1.0 (2021-12-25)

  • feat: add supports the use of open and close properties for each style
  • fix: codes for methods ansi256() and bgAnsi256()
  • chore: added demo to npm package
  • chore: update package.json
  • docs: update readme

1.0.0 (2021-12-24)

First release