🌜
🌞
kleur

kleur

v4.1.5

The fastest Node.js library for formatting terminal text with ANSI colors~!

npm install kleur

README

kleur
The fastest Node.js library for formatting terminal text with ANSI colors~!

Features


As of v3.0 the Chalk-style syntax (magical getter) is no longer used.
Please visit History for migration paths supporting that syntax.


Install

$ npm install --save kleur

Usage

import kleur from 'kleur';

// basic usage
kleur.red('red text');

// chained methods
kleur.blue().bold().underline('howdy partner');

// nested methods
kleur.bold(`${ white().bgRed('[ERROR]') } ${ kleur.red().italic('Something happened')}`);

Chained Methods

const { bold, green } = require('kleur');

console.log(bold().red('this is a bold red message'));
console.log(bold().italic('this is a bold italicized message'));
console.log(bold().yellow().bgRed().italic('this is a bold yellow italicized message'));
console.log(green().bold().underline('this is a bold green underlined message'));
chained method

Nested Methods

const { yellow, red, cyan } = require('kleur');

console.log(yellow(`foo ${red().bold('red')} bar ${cyan('cyan')} baz`));
console.log(yellow('foo ' + red().bold('red') + ' bar ' + cyan('cyan') + ' baz'));
nested method

Conditional Support

Toggle color support as needed; kleur includes simple auto-detection which may not cover all cases.

Note: Both kleur and kleur/colors share the same detection logic.

import kleur from 'kleur';

// manually disable
kleur.enabled = false;

// or use another library to detect support
kleur.enabled = require('color-support').level > 0;

console.log(kleur.red('I will only be colored red if the terminal supports colors'));

Important:
Colors will be disabled automatically in non TTY contexts. For example, spawning another process or piping output into another process will disable colorization automatically. To force colors in your piped output, you may do so with the FORCE_COLOR=1 environment variable:

$ node app.js #=> COLORS
$ node app.js > log.txt  #=> NO COLORS
$ FORCE_COLOR=1 node app.js > log.txt #=> COLORS
$ FORCE_COLOR=0 node app.js > log.txt #=> NO COLORS

API

Any kleur method returns a String when invoked with input; otherwise chaining is expected.

It's up to the developer to pass the output to destinations like console.log, process.stdout.write, etc.

The methods below are grouped by type for legibility purposes only. They each can be chained or nested with one another.

Colors:

black — red — green — yellow — blue — magenta — cyan — white — gray — grey

Backgrounds:

bgBlack — bgRed — bgGreen — bgYellow — bgBlue — bgMagenta — bgCyan — bgWhite

Modifiers:

reset — bold — dim — italic* — underline — inverse — hidden — strikethrough*

* Not widely supported

Individual Colors

When you only need a few colors, it doesn't make sense to import all of kleur because, as small as it is, kleur is not treeshakeable, and so most of its code will be doing nothing. In order to fix this, you can import from the kleur/colors submodule which fully supports tree-shaking.

The caveat with this approach is that color functions are not chainable~!
Each function receives and colorizes its input. You may combine colors, backgrounds, and modifiers by nesting function calls within other functions.

// or: import * as kleur from 'kleur/colors';
import { red, underline, bgWhite } from 'kleur/colors';

red('red text');
//~> kleur.red('red text');

underline(red('red underlined text'));
//~> kleur.underline().red('red underlined text');

bgWhite(underline(red('red underlined text w/ white background')));
//~> kleur.bgWhite().underline().red('red underlined text w/ white background');

Note: All the same colors, backgrounds, and modifiers are available.

Conditional Support

The kleur/colors submodule also allows you to toggle color support, as needed.
It includes the same initial assumptions as kleur, in an attempt to have colors enabled by default.

Unlike kleur, this setting exists as kleur.$.enabled instead of kleur.enabled:

import * as kleur from 'kleur/colors';
// or: import { $, red } from 'kleur/colors';

// manually disabled
kleur.$.enabled = false;

// or use another library to detect support
kleur.$.enabled = require('color-support').level > 0;

console.log(red('I will only be colored red if the terminal supports colors'));

Benchmarks

Using Node v10.13.0

Load time

chalk        :: 5.303ms
kleur        :: 0.488ms
kleur/colors :: 0.369ms
ansi-colors  :: 1.504ms

Performance

# All Colors
  ansi-colors      x 177,625 ops/sec ±1.47% (92 runs sampled)
  chalk            x 611,907 ops/sec ±0.20% (92 runs sampled)
  kleur            x 742,509 ops/sec ±1.47% (93 runs sampled)
  kleur/colors     x 881,742 ops/sec ±0.19% (98 runs sampled)

# Stacked colors
  ansi-colors      x  23,331 ops/sec ±1.81% (94 runs sampled)
  chalk            x 337,178 ops/sec ±0.20% (98 runs sampled)
  kleur            x  78,299 ops/sec ±1.01% (97 runs sampled)
  kleur/colors     x 104,431 ops/sec ±0.22% (97 runs sampled)

# Nested colors
  ansi-colors      x  67,181 ops/sec ±1.15% (92 runs sampled)
  chalk            x 116,361 ops/sec ±0.63% (94 runs sampled)
  kleur            x 139,514 ops/sec ±0.76% (95 runs sampled)
  kleur/colors     x 145,716 ops/sec ±0.97% (97 runs sampled)

History

This project originally forked ansi-colors.

Beginning with [email protected], the Chalk-style syntax (magical getter) has been replaced with function calls per key:

// Old:
c.red.bold.underline('old');

// New:
c.red().bold().underline('new');

As I work more with Rust, the newer syntax feels so much better & more natural!

If you prefer the old syntax, you may migrate to ansi-colors or newer chalk releases.
Versions below [email protected] have been officially deprecated.

License

MIT © Luke Edwards

Release Notes

4.1.5
By Luke Edwards • Published on June 26, 2022

Patches

  • Add "types" export conditions for Node16 TypeScript module resolution (#57): 06f28e0 Thank you @calebeby~!
  • Handle undefined process.env with fallback (#54): ec20016 For browser/vite support. Thank you @farnabaz~!

Full Changelog: https://github.com/lukeed/kleur/compare/v4.1.4...v4.1.5

4.1.4
By Luke Edwards • Published on January 22, 2021

Chores

  • Replace includes() usage with indexOf to allow support for older browsers (#45): 86a7db8 No behavioral differences. Simply allows kleur to run in old browsers (eg, IE8-11) without requiring a polyfill. Thank you @Krinkle~!

  • Update benchmarks to reflect includes -> indexOf update: 19764d4

4.1.3
By Luke Edwards • Published on September 30, 2020

Patches

  • Add existence process.stdout check for browser-like polyfills (#42): 01963cc Bundlers like parcel, webpack, and browserify polyfill process but don't include a stdout implementation. Thank you @tinchoz49~!
4.1.2
By Luke Edwards • Published on September 26, 2020

Patches

  • Ensure NO_COLOR disables colorization if any value is received (#38, #39, #40, #41): ef5d4a8, b329629 Now properly adheres to the NO_COLOR spec. Thank you @stramel and @chocolateboy~!

Chores

  • Adds tests to ensure FORCE_COLOR= works as expected (#41): b329629 Much like NO_COLOR, use of FORCE_COLOR= is expected to be truthy.
4.1.1
By Luke Edwards • Published on August 19, 2020

Patches

  • (types): Ensure kleur/colors type definitions can be resolved: 06923d0, cc66a6f
4.1.0
By Luke Edwards • Published on August 13, 2020

Features

Chores

4.0.3
By Luke Edwards • Published on July 31, 2020

Patches

  • Ensure process is defined before setting process-based values (#36): 303e502 This allows for kleur to be imported into browsers without any bundle-shimming.

    NOTE: ANSI code support varies between browsers, but typically colors and background-colors work (never modifiers).

4.0.2
By Luke Edwards • Published on June 24, 2020

Patches

  • Disable colorization if inside a TTY context (#33): 5c7353f Thank you @ai~!

    # Before:
    $ npx app.js > log.txt
    #=> The `log.txt` filled with ANSI codes 
    
    # After:
    $ npx app.js > log.txt
    #=> The `log.txt` is plain text
    
    # OVERRIDE:
    $ FORCE_COLOR=1 npx app.js > log.txt
    #=> The `log.txt` filled with ANSI codes; as requested
    

Chores

  • Add bash tests for ENV detection: 5c7353f
  • Update README with TTY explainer and example: 3a6a272, 3b3742a
  • Update test runner version: 5fd93ba
4.0.1
By Luke Edwards • Published on June 19, 2020

Patches

  • Revert to Node 6.x minimum support: 8c01d93 The code works perfectly in that environment, so there's no reason not to.
    Truth be told, it was only bumped to 10.x because of the test runner constraint.

  • (types) fix kleur/colors overloaded definition: f2f33a8 Original print order assumed that every export returned null, which is not true.

4.0.0
By Luke Edwards • Published on June 17, 2020

Breaking

The minimum Node.js runtime increased from 6.x to 10.x since 10.x is the oldest active LTS version.
If you need to continue supporting Node 6.x, either continue using [email protected] or ignore the "engines" constraint of [email protected] – its CommonJS files will still execute in a Node 6.x environment.

Features

  • Added native ESM support with exports map (for Node 12.18.x, Node 14+) (#30): 2da16a9 Thank you @kristoferbaxter~!

  • Added module package entry (for bundler and PikaCDN) (#31): 2da16a9

  • Added new kleur/colors entry module: 049c080

These changes allow for import statements with kleur.
It's done in a way such that Node.js environments that natively support import will work. For those that don't and are using webpack/Rollup, the "module" entry is made available so that you can still take advantage of the ESM format.

We took this idea one step further with kleur/colors – which individually exports each color, modifier, and background function. This allows you to import only the methods you need, and the unused pieces of code are detached from your code. In other words, kleur/colors is 100% treeshakeable, which is a big advantage of the ESM format. Node.js (with native ESM support), Rollup, and webpack benefit from this, which means that your programs only include/load the kleur code you use.

If you're not ready to use ESM yet, require statements still work for both modules in all environments.

See the Individual Colors documentation for more info

import kleur from 'kleur';
import * as colors from 'kleur/colors';

console.log(
  kleur.underline().green('kleur natively supports ESM~!')
);

console.log(
  colors.white(colors.italic(`... so does "${ colors.green('kleur/colors') }"~!`))
);

Chores

  • Migrate CI from TravisCI to GitHub Actions: f0b5da4, 88f9f72
  • Move to c8 for code coverage: 06e3ba4
  • Update test runner, include kleur/colors tests: f39b294
  • Update benchmarks: 46cc8d8, 61d0d58, 049c080
  • Update README: e2291ef, 9f09249, 840d3c0

General

License
MIT
Typescript Types
Built-in
Tree-shakeable
Yes

Popularity

GitHub Stargazers
1,379
Community Interest
1,278
Number of Forks
45

Maintenance

Commits
10/219/2203
Last Commit
Jun 26, 2022
Open Issues
6
Closed Issues
17
Open Pull Requests
4
Closed Pull Requests
9

Versions

Versions Released
10/219/2201
Latest Version Released
Current Tags
latest4.1.5

Dependencies

Dependencies (0)
Dev Dependencies (2)

Contributors

lukeed
lukeed
Commits: 105
madhavarshney
madhavarshney
Commits: 2
stramel
stramel
Commits: 2
Krinkle
Krinkle
Commits: 1
ai
ai
Commits: 1
Rich-Harris
Rich-Harris
Commits: 1
marvinhagemeister
marvinhagemeister
Commits: 1
kristoferbaxter
kristoferbaxter
Commits: 1
lumio
lumio
Commits: 1
styfle
styfle
Commits: 1
Hammster
Hammster
Commits: 1
DanielRuf
DanielRuf
Commits: 1
jorgebucaran
jorgebucaran
Commits: 1
tinchoz49
tinchoz49
Commits: 1