Skip to main content
The highlight() function is the main entry point for Code Syntactic Sugar. It takes JavaScript/TypeScript code as a string and returns highlighted React elements ready for rendering.

Signature

function highlight(
  code: string,
  config?: CodeSyntacticSugarConfig
): ReactElement

Parameters

code
string
required
The JavaScript or TypeScript code to highlight as a string.
config
CodeSyntacticSugarConfig
Optional configuration object for customizing the highlighting behavior.

Returns

ReactElement
ReactElement
A React element containing the highlighted code. The output is a tree of <span> elements with appropriate CSS classes for styling.

Example

import { highlight } from 'code-syntactic-sugar';
import { createRoot } from 'react-dom/client';

function CodeBlock() {
  const code = `
  const a = 10;
  const b = 20;
  console.log(a + b);
  `.trim();

  const codeLines = highlight(code);

  return <code>{codeLines}</code>;
}

const root = createRoot(document.querySelector('#app > pre'));
root.render(<CodeBlock />);

Example with Line Modifiers

import { highlight } from 'code-syntactic-sugar';

function CodeBlock() {
  const code = `
    let a = 1;
    let b = 10;
    const result = a + b;
    console.log(a);
    console.log(b);
    console.log(result);
  `.trim();

  const codeLines = highlight(code, {
    modifiers: {
      highlightedLines: [1, 2],
      addedLines: [4, 5],
      removedLines: [3],
    },
  });

  return <code>{codeLines}</code>;
}

Notes

The highlight() function internally calls tokenize() to parse the code, then generate() to create line structures, and finally converts them to React elements.
Line numbers in modifier arrays are 1-indexed (not 0-indexed). Out-of-bounds line numbers are automatically ignored.
When multiple modifiers are applied to the same line, the order of precedence is:
  1. highlightedLines (highest priority)
  2. addedLines
  3. removedLines (lowest priority)
The output requires React to be installed in your project as it returns React elements.

Build docs developers (and LLMs) love