Skip to content

Instantly share code, notes, and snippets.

@forivall
Last active February 5, 2026 19:16
Show Gist options
  • Select an option

  • Save forivall/25c042e0c4e5752ea2e6f1ba94211889 to your computer and use it in GitHub Desktop.

Select an option

Save forivall/25c042e0c4e5752ea2e6f1ba94211889 to your computer and use it in GitHub Desktop.
drop-in node.js chalk replacement using util.styleText. < 2k bytes unminified, 600 bytes minified, 394 min + gzip
import util from 'node:util';
/** @typedef {Extract<Parameters<typeof util.styleText>[0], string>} TextStyle */
// prettier-ignore
const baseColors = /** @type {const} */ (
['black', 'blue', 'cyan', 'green', 'gray', 'grey', 'magenta', 'red', 'white', 'yellow']
);
/** @typedef {typeof baseColors[number]} BaseColor */
const colorsAndBg = /** @type {const} */ (['bg', '']).flatMap(
/** @template T @param {T} p @returns {p extends '' ? BaseColor : `${p}${Capitalize<BaseColor>}`} */ (
p
) => baseColors.map((b) => `${p}${p ? b[0].toUpperCase() + b.slice(1) : b}`)
);
/** @type {(c: typeof colorsAndBg[number]) => c is Extract<typeof c, `${string}y`>} */
const isGrey = (c) => /y$/.test(c);
const allColors = colorsAndBg.flatMap((c) =>
isGrey(c) ? c : /** @type {const} */ ([c, `${c}Bright`])
);
// prettier-ignore
const modifiers = /** @type {const} */ ([
'reset', 'bold', 'italic', 'dim', 'blink', 'inverse', 'hidden', 'none',
'underline', 'doubleunderline', 'strikethrough', 'framed', 'overlined',
]);
/** @typedef {typeof allColors[number] | typeof modifiers[number]} KnownColor */
/** @typedef {{[K in KnownColor]: MiniChalk} & {styles: TextStyle[]} & (text: string) => string} MiniChalk */
const chalkProperties = Object.fromEntries(
[...allColors, ...modifiers].map(
/** @returns {[KnownColor, PropertyDescriptor]} */ (color) => [
color,
// prettier-ignore
{ enumerable: true, get() { return createChalk([...this.styles, color]) } },
]
)
);
/**
* @param {TextStyle[]} styles
* @returns {MiniChalk}
*/
const createChalk = (styles) => {
const chalk = (text) => util.styleText(styles, text);
Object.defineProperties(chalk, chalkProperties);
chalk.styles = styles;
return chalk;
};
export const chalk = createChalk([]);
export default chalk;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment