ANSI Fragments for CLI Styling

0.2.1 · active · verified Wed Apr 22

ansi-fragments is a compact JavaScript library designed for constructing aesthetically pleasing command-line interface (CLI) outputs using ANSI escape codes. Currently at version 0.2.1, it adopts a unique builder-pattern approach, allowing developers to compose styled text fragments programmatically. The library provides functions like `color`, `modifier`, `container`, `pad`, `fixed`, `ifElse`, and `provide` to encapsulate styling logic. Its core differentiator is the explicit fragment building and the `.build()` method, which converts the fragment tree into a single ANSI-encoded string. While a relatively new project, its focus is on providing a 'nice DX' for structured CLI logging rather than offering an exhaustive list of all possible ANSI features. Release cadence is infrequent, typical for a micro-utility library in its early stages.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating complex, conditional, and fixed-width CLI log messages using various ansi-fragments builders like color, modifier, container, fixed, and ifElse.

import { color, modifier, pad, container, fixed, ifElse } from 'ansi-fragments';

const generateLogMessage = (level, message, timestamp, hasError) => {
  const levelFragment = ifElse(
    () => hasError,
    color('red', modifier('bold', level.toUpperCase())),
    color('green', modifier('italic', level))
  );

  const timeFragment = color('gray', `[${timestamp}]`);

  const paddedMessage = container(
    fixed(8, 'start', levelFragment),
    pad(1),
    timeFragment,
    pad(1),
    message
  );

  return paddedMessage.build();
};

const now = new Date().toISOString().slice(11, 19);

console.log(generateLogMessage('success', 'Operation completed successfully!', now, false));
console.log(generateLogMessage('warning', 'Cache might be stale.', now, false));
console.log(generateLogMessage('error', 'Failed to connect to database.', now, true));
console.log(generateLogMessage('info', 'Processing batch job...', now, false));
// Simulate a long message being truncated by fixed()
console.log(generateLogMessage('debug', 'This is a very long debug message that should be truncated.', now, false));

// Example without fixed, just showing container and colors
const header = container(
  color('cyan', '📦 Package Installer'),
  pad(1, '-'),
  color('magenta', 'v1.2.3')
).build();
console.log(header);

view raw JSON →