or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel--highlight

Syntax highlight JavaScript strings for output in terminals.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@babel/highlight@7.25.x

To install, run

npx @tessl/cli install tessl/npm-babel--highlight@7.25.0

index.mddocs/

@babel/highlight

@babel/highlight provides JavaScript and JSX syntax highlighting specifically designed for terminal output. It parses JavaScript code using the js-tokens library and applies ANSI color formatting using picocolors to enhance code readability in command-line interfaces and development tools.

Package Information

  • Package Name: @babel/highlight
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @babel/highlight

Core Imports

import highlight, { shouldHighlight } from "@babel/highlight";

For CommonJS:

const highlight = require("@babel/highlight");
const { shouldHighlight } = require("@babel/highlight");

Basic Usage

import highlight, { shouldHighlight } from "@babel/highlight";

// Basic syntax highlighting
const code = `
function greet(name) {
  console.log(\`Hello, \${name}!\`);
  return true;
}
`;

// Check if highlighting is supported
if (shouldHighlight({})) {
  const highlighted = highlight(code);
  console.log(highlighted); // Outputs colorized code
} else {
  console.log(code); // Fallback to plain text
}

// Force colors even if terminal doesn't support them
const forceHighlighted = highlight(code, { forceColor: true });

Architecture

@babel/highlight is built around several key components:

  • Token Parser: Uses js-tokens library to parse JavaScript/JSX into categorized tokens
  • Color Engine: Applies ANSI colors using picocolors (modern) or chalk (legacy Babel 7)
  • Terminal Detection: Automatically detects terminal color capabilities via environment variables
  • Token Classification: Intelligent categorization of JavaScript tokens (keywords, strings, comments, etc.)
  • Template Literal Support: Special handling for template strings with embedded expressions (Babel 8 tokenizes template heads, middles, and tails separately)

Capabilities

Syntax Highlighting

Main function to highlight JavaScript/JSX code with terminal colors.

/**
 * Highlight JavaScript code with syntax coloring for terminal output
 * @param code - JavaScript/JSX code string to highlight
 * @param options - Optional configuration object
 * @returns String with ANSI color codes applied for terminal display
 */
function highlight(code: string, options?: Options): string;

interface Options {
  /** Force color output even when terminal doesn't support colors */
  forceColor?: boolean;
}

Usage Examples:

import highlight from "@babel/highlight";

// Basic highlighting
const simpleCode = "const x = 42;";
const highlighted = highlight(simpleCode);

// JSX highlighting
const jsxCode = `
function App() {
  return <div className="app">Hello World</div>;
}
`;
const highlightedJsx = highlight(jsxCode);

// Force colors for non-interactive environments
const forcedColors = highlight(simpleCode, { forceColor: true });

// Complex code with various token types
const complexCode = `
// Function with template literals and JSX
async function fetchUser(id) {
  const response = await fetch(\`/api/users/\${id}\`);
  if (!response.ok) {
    throw new Error("Failed to fetch user");
  }
  return response.json();
}

const UserCard = ({ user }) => (
  <div className="user-card">
    <h2>{user.name}</h2>
    <p>Age: {user.age || "Unknown"}</p>
  </div>
);
`;
const highlightedComplex = highlight(complexCode, { forceColor: true });

Color Support Detection

Determines whether code should be highlighted based on terminal capabilities and options.

/**
 * Whether the code should be highlighted given the passed options
 * @param options - Configuration object with optional forceColor
 * @returns Boolean indicating if highlighting should be applied
 */
function shouldHighlight(options: Options): boolean;

Usage Examples:

import { shouldHighlight } from "@babel/highlight";

// Check terminal color support
if (shouldHighlight({})) {
  console.log("Terminal supports colors");
}

// Always returns true when forceColor is set
const forced = shouldHighlight({ forceColor: true }); // true

// Use in conditional highlighting
const code = "const greeting = 'Hello';";
const output = shouldHighlight({}) 
  ? highlight(code) 
  : code;

Legacy Chalk Support (Babel 7 only)

Returns chalk instance for legacy compatibility (not available in Babel 8).

/**
 * Get chalk instance for legacy compatibility (Babel 7 only)
 * @param options - Configuration object with optional forceColor
 * @returns Chalk instance configured for color support
 */
function getChalk(options: Options): any;

Note: This function is only available in Babel 7 mode (when BABEL_8_BREAKING is not set) and is not exported in ES modules. It's accessed via CommonJS exports.

// Only available in Babel 7 with CommonJS
const { getChalk } = require("@babel/highlight");
const chalk = getChalk({ forceColor: true });

Types

interface Options {
  /** Force color output even when terminal doesn't support colors */
  forceColor?: boolean;
}

Token Categories

The highlighting system categorizes JavaScript tokens into the following types with associated colors:

  • Keywords: cyan - JavaScript keywords (function, const, let, if, etc.)
  • Capitalized: yellow - Capitalized identifiers (typically class names)
  • JSX Identifiers: yellow - JSX tag names and component names
  • Punctuators: yellow - Operators and punctuation (=, +, etc.)
  • Brackets: uncolored - Bracket tokens ({}, [], ()) remain uncolored for better readability
  • Numbers: magenta - Numeric literals (42, 3.14, 0xFF)
  • Strings: green - String literals and template strings
  • Regular Expressions: magenta - RegExp literals (/pattern/flags)
  • Comments: gray - Single-line (//) and multi-line (/* */) comments
  • Invalid: white on red background - Invalid syntax tokens

Environment Configuration

The package respects environment variables for color control:

  • FORCE_COLOR=0 or FORCE_COLOR=false: Disables colors regardless of terminal support
  • Terminal color capability detection via picocolors library
  • forceColor option overrides automatic detection

Version Differences

Babel 7:

  • Uses js-tokens v4
  • Includes chalk support via getChalk function
  • Legacy JSX tag detection using regex patterns

Babel 8:

  • Uses js-tokens v8 with improved JSX support
  • Picocolors only (no chalk)
  • Enhanced template literal handling with separate TemplateHead, TemplateMiddle, and TemplateTail token processing
  • Better token type classification