or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-colors.mdbackground-colors.mdbasic-colors.mdcolor-support.mdconfiguration.mdindex.mdtext-styling.md
tile.json

configuration.mddocs/

Configuration

Creating custom Chalk instances and managing color support levels for different environments and use cases.

Capabilities

Chalk Constructor

Creates new Chalk instances with custom configuration options.

/**
 * Constructor for creating custom Chalk instances
 * @param options - Configuration options for the instance
 * @returns New ChalkInstance with specified configuration
 */
const Chalk: new (options?: Options) => ChalkInstance;

interface Options {
  /**
   * Specify the color support level for Chalk
   * By default, color support is automatically detected based on the environment
   * 
   * Levels:
   * - 0: All colors disabled
   * - 1: Basic 16 colors support
   * - 2: ANSI 256 colors support
   * - 3: Truecolor 16 million colors support
   */
  readonly level?: ColorSupportLevel;
}

type ColorSupportLevel = 0 | 1 | 2 | 3;

Usage Examples:

import { Chalk } from 'chalk';

// Create instance with no colors (useful for testing or file output)
const noColorChalk = new Chalk({ level: 0 });
console.log(noColorChalk.red('This appears as plain text'));

// Create instance with basic 16-color support only
const basicChalk = new Chalk({ level: 1 });
console.log(basicChalk.red('Basic red color'));
console.log(basicChalk.rgb(255, 0, 0)('RGB red downsampled to basic red'));

// Create instance with 256-color support
const ansi256Chalk = new Chalk({ level: 2 });
console.log(ansi256Chalk.ansi256(196)('256-color red'));
console.log(ansi256Chalk.rgb(255, 0, 0)('RGB red downsampled to 256-color'));

// Create instance with full truecolor support
const truecolorChalk = new Chalk({ level: 3 });
console.log(truecolorChalk.rgb(255, 128, 64)('Full RGB orange'));
console.log(truecolorChalk.hex('#FF8040')('Full HEX orange'));

Level Property

Access and modify the color support level of existing Chalk instances.

/**
 * The color support level for the Chalk instance
 * Can be read or modified to change color behavior
 */
level: ColorSupportLevel;

Usage Examples:

import chalk from 'chalk';

// Check current level
console.log('Current color level:', chalk.level);

// Temporarily disable colors
const originalLevel = chalk.level;
chalk.level = 0;
console.log(chalk.red('This appears as plain text'));

// Restore colors
chalk.level = originalLevel;
console.log(chalk.red('This appears in red'));

// Set to basic colors only
chalk.level = 1;
console.log(chalk.rgb(255, 128, 64)('RGB color downsampled to basic'));

Configuration Patterns

Common patterns for configuring Chalk in different environments:

Environment-Based Configuration

import chalk, { Chalk } from 'chalk';

// Configure based on environment
function createChalkInstance() {
  if (process.env.NODE_ENV === 'test') {
    // Disable colors in test environment
    return new Chalk({ level: 0 });
  }
  
  if (process.env.CI) {
    // Use basic colors in CI environments
    return new Chalk({ level: 1 });
  }
  
  // Use default auto-detection in other environments
  return chalk;
}

const logger = createChalkInstance();
console.log(logger.green('Environment-appropriate colored output'));

Multiple Output Targets

import { Chalk } from 'chalk';

// Different configurations for different outputs
const consoleChalk = new Chalk({ level: 3 }); // Full colors for console
const fileChalk = new Chalk({ level: 0 });    // No colors for file output
const logChalk = new Chalk({ level: 1 });     // Basic colors for logs

function logMessage(message, type = 'info') {
  const timestamp = new Date().toISOString();
  
  // Console output (with full colors)
  console.log(consoleChalk.blue(`[${timestamp}]`) + ' ' + consoleChalk.green(message));
  
  // File output (no colors)
  // fs.appendFileSync('app.log', fileChalk.blue(`[${timestamp}]`) + ' ' + message + '\n');
  
  // Structured log (basic colors)  
  const logEntry = logChalk.cyan(`[${type.toUpperCase()}]`) + ' ' + message;
  console.log('Log entry:', logEntry);
}

logMessage('Application started', 'info');

Dynamic Color Level Adjustment

import chalk from 'chalk';

// Function to adjust color level based on conditions
function adjustColorLevel(enabled, advanced = false) {
  if (!enabled) {
    chalk.level = 0;  // No colors
  } else if (!advanced) {
    chalk.level = 1;  // Basic colors only
  } else {
    chalk.level = 3;  // Full color support
  }
}

// Usage with command line flags
const colorEnabled = !process.argv.includes('--no-color');
const advancedColors = process.argv.includes('--color-256') || process.argv.includes('--color-16m');

adjustColorLevel(colorEnabled, advancedColors);

console.log(chalk.red('Color output based on command line flags'));

Instance Isolation

import { Chalk } from 'chalk';

// Create isolated instances for different purposes
class Logger {
  constructor(options = {}) {
    this.chalk = new Chalk({ level: options.colorLevel || 2 });
    this.name = options.name || 'Logger';
  }
  
  info(message) {
    console.log(this.chalk.blue(`[${this.name}]`) + ' ' + message);
  }
  
  warn(message) {
    console.log(this.chalk.yellow(`[${this.name}]`) + ' ' + message);
  }
  
  error(message) {
    console.log(this.chalk.red(`[${this.name}]`) + ' ' + message);
  }
}

// Different loggers with different color configurations
const appLogger = new Logger({ name: 'APP', colorLevel: 3 });
const dbLogger = new Logger({ name: 'DB', colorLevel: 1 });
const testLogger = new Logger({ name: 'TEST', colorLevel: 0 });

appLogger.info('Application message with full colors');
dbLogger.warn('Database warning with basic colors');
testLogger.error('Test error message with no colors');

Color Level Detection

Understanding how Chalk determines color support levels:

import chalk, { supportsColor } from 'chalk';

// Check what color support was detected
console.log('Detected color support:', supportsColor);

if (supportsColor) {
  console.log('Color level:', supportsColor.level);
  console.log('Has basic colors:', supportsColor.hasBasic);
  console.log('Has 256 colors:', supportsColor.has256);
  console.log('Has 16m colors:', supportsColor.has16m);
} else {
  console.log('No color support detected');
}

// Override detection if needed
if (supportsColor && supportsColor.level < 2) {
  console.log('Terminal supports basic colors, but forcing 256-color mode');
  chalk.level = 2;
}

Best Practices

Guidelines for configuring Chalk effectively:

import { Chalk } from 'chalk';

// 1. Respect user preferences
function createUserAwareChalk() {
  // Check for NO_COLOR environment variable (standard)
  if (process.env.NO_COLOR) {
    return new Chalk({ level: 0 });
  }
  
  // Check for FORCE_COLOR environment variable
  if (process.env.FORCE_COLOR) {
    const level = parseInt(process.env.FORCE_COLOR, 10);
    if (level >= 0 && level <= 3) {
      return new Chalk({ level });
    }
  }
  
  // Use default detection
  return new Chalk();
}

// 2. Provide configuration options
class ColorizedOutput {
  constructor(options = {}) {
    this.chalk = new Chalk({
      level: options.colors === false ? 0 : options.colorLevel
    });
  }
  
  render(text, style = 'normal') {
    switch (style) {
      case 'success': return this.chalk.green(text);
      case 'warning': return this.chalk.yellow(text);
      case 'error': return this.chalk.red(text);
      default: return this.chalk(text);
    }
  }
}

// Usage
const output = new ColorizedOutput({ colors: true, colorLevel: 2 });
console.log(output.render('Success message', 'success'));

// 3. Test with different color levels
function testColorLevels(text) {
  [0, 1, 2, 3].forEach(level => {
    const testChalk = new Chalk({ level });
    console.log(`Level ${level}:`, testChalk.rgb(255, 128, 0)(text));
  });
}

testColorLevels('Color level comparison');