Syntax highlight JavaScript strings for output in terminals.
npx @tessl/cli install tessl/npm-babel--highlight@7.25.0@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.
npm install @babel/highlightimport highlight, { shouldHighlight } from "@babel/highlight";For CommonJS:
const highlight = require("@babel/highlight");
const { shouldHighlight } = require("@babel/highlight");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 });@babel/highlight is built around several key components:
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 });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;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 });interface Options {
/** Force color output even when terminal doesn't support colors */
forceColor?: boolean;
}The highlighting system categorizes JavaScript tokens into the following types with associated colors:
cyan - JavaScript keywords (function, const, let, if, etc.)yellow - Capitalized identifiers (typically class names)yellow - JSX tag names and component namesyellow - Operators and punctuation (=, +, etc.)uncolored - Bracket tokens ({}, [], ()) remain uncolored for better readabilitymagenta - Numeric literals (42, 3.14, 0xFF)green - String literals and template stringsmagenta - RegExp literals (/pattern/flags)gray - Single-line (//) and multi-line (/* */) commentswhite on red background - Invalid syntax tokensThe package respects environment variables for color control:
FORCE_COLOR=0 or FORCE_COLOR=false: Disables colors regardless of terminal supportforceColor option overrides automatic detectionBabel 7:
getChalk functionBabel 8: