Tiny & Fast JavaScript Syntax Highlighting Library – Speed Highlight

Category: Javascript | August 25, 2026
Authorspeed-highlight
Last UpdateAugust 25, 2026
LicenseMIT
Views37 views
Tiny & Fast JavaScript Syntax Highlighting Library – Speed Highlight

Speed Highlight JS is a lightweight and fast JavaScript syntax highlighting library that converts code blocks into color-coded HTML using a small core engine and per-language tokenizers.

You can use it to highlight code samples on documentation sites, blog posts, admin dashboards, and pages that display JavaScript, Python, SQL, YAML, or other source code.

The library scans plain text inside a div or code element and assigns a CSS class to each token. A linked stylesheet then controls the final colors.

Features:

  • Formats multi-line code blocks and inline code elements.
  • 30+ programming and markup languages.
  • Loads built-in language definitions on demand.
  • Generates highlighted HTML strings for custom renderers.
  • Detects selected programming languages from raw source text.
  • Supports optional line-number removal.
  • Includes browser themes for light and dark interfaces.
  • Prints ANSI-colored code in terminal output.
  • Accepts custom language definitions.

Speed Highlight JS vs. Prism, highlight.js, and Shiki

Speed Highlight JS targets browser projects that need a small syntax highlighting layer for common languages. It uses shj-lang-* classes, loads language definitions on demand, and also includes a terminal adapter for Node.js and Deno workflows.

Prism, highlight.js, and Shiki solve the same general problem, but they fit different rendering paths and content requirements.

LibraryChoose It WhenKey Difference
Speed Highlight JSYour site needs small browser-side highlighting for documentation, demos, or dynamic code previews.Uses shj-lang-* classes, supports selected language detection, and also formats terminal output.
PrismYour code blocks need features such as copy buttons, toolbars, line numbers, or a larger plugin ecosystem.Offers more extensions for browser documentation sites.
highlight.jsYour content includes unknown, pasted, imported, or user-submitted code.Focuses on broad language coverage and automatic language detection.
ShikiYour documentation site highlights code during static builds or server-side rendering.Uses TextMate grammars and editor-style themes for generated HTML output.

How To Use It

Installation

Install the package through npm for ES module projects and bundlers.

npm install @speed-highlight/core

CDN

You can also load a CSS theme and import the browser module from a CDN.

<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@speed-highlight/core@2/dist/themes/default.css"
/>
<script type="module">
  import {
    highlightAll
  } from 'https://cdn.jsdelivr.net/npm/@speed-highlight/core@2/dist/index.js';
  await highlightAll();
</script>

Basic Usage

Place the language name in a shj-lang-* class. A div renders as a block. A code element renders inline. Import a CSS theme before processing the page, then call highlightAll() after the source elements exist in the document.

<div class="shj-lang-js">
const formatPrice = (amount) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  }).format(amount);
};
</div>
<code class="shj-lang-css">color: rebeccapurple;</code>
import '@speed-highlight/core/themes/github-light.css';
import { highlightAll } from '@speed-highlight/core';
await highlightAll();

Show Line Numbers

Line numbers are disabled by default. Set showLineNumbers to true for block output that needs a numbered gutter.

import { highlightElement } from '@speed-highlight/core';
const codeBlock = document.querySelector('#script-preview');
await highlightElement(codeBlock, 'js', {
  showLineNumbers: true
});

Highlight Dynamic JSON Responses

Write dynamic source into textContent before calling highlightElement(). The library reads that plain text and replaces the element content with token markup.

<div id="payload-preview"></div>
import { highlightElement } from '@speed-highlight/core';
const payloadPreview = document.querySelector('#payload-preview');
const payload = {
  status: 'ready',
  records: 12,
  endpoint: '/api/projects'
};
payloadPreview.textContent = JSON.stringify(payload, null, 2);
await highlightElement(payloadPreview, 'json', {
  showLineNumbers: true
});

Detect the Language of Pasted Code

The optional detector is a small import outside the core entry. It recognizes Assembly, Bash, C, CSS, Diff, Dockerfile, Go, HTML, HTTP, Java, Lua, Makefile, Markdown, Perl, Python, Rust, SQL, TypeScript-style syntax, URI, XML, and YAML. It returns plain when the score is too low. JavaScript-style source currently shares the TypeScript detection rule. JavaScript snippets can resolve to ts.

<div id="code-preview"></div>
import { highlightElement } from '@speed-highlight/core';
import { detectLanguage } from '@speed-highlight/core/detect';
const sourceCode = `
def build_slug(title):
    return title.lower().replace(" ", "-")
`;
const preview = document.querySelector('#code-preview');
const language = detectLanguage(sourceCode);
preview.textContent = sourceCode;
await highlightElement(preview, language);

Generate Highlighted HTML for Components and SSR

highlightHTML() returns an HTML string and does not access the DOM. It escapes ampersands and angle brackets from the input before token spans are written. Browser renderers should keep the shj-lang-* language class and a display class on the host element. The CSS theme uses those classes to style the result.

<div
  id="generated-preview"
  class="shj-lang-ts shj-block"
></div>
import { highlightHTML } from '@speed-highlight/core';
const sourceCode = `
type Project = {
  id: number;
  title: string;
};
`;
const highlightedMarkup = await highlightHTML(
  sourceCode,
  'ts',
  {
    block: true,
    showLineNumbers: true
  }
);
document.querySelector('#generated-preview').innerHTML =
  highlightedMarkup;

Highlight Code in Node.js Terminals

highlightANSI() returns a string with ANSI escape sequences. A terminal theme is required and comes from a JavaScript theme file.

import { highlightANSI } from '@speed-highlight/core';
import theme from '@speed-highlight/core/themes/atom-dark.js';
const terminalOutput = await highlightANSI(
  'export const isPublished = true;',
  'js',
  theme
);
console.log(terminalOutput);

Custom Terminal Theme

Terminal themes map token types to ANSI escape sequences. The termcolor.js helpers expose common terminal colors for custom theme objects.

import * as color from '@speed-highlight/core/themes/termcolor.js';
const terminalTheme = {
  kwd: color.red,
  str: color.green,
  cmnt: color.gray
};

Deno

Deno can load the browser-independent highlighting functions and terminal themes from the published Deno module.

import { highlightANSI }
  from 'https://deno.land/x/speed_highlight_js/dist/index.js';
import theme
  from 'https://deno.land/x/speed_highlight_js/dist/themes/default.js';
console.log(
  await highlightANSI('console.log("Build finished")', 'js', theme)
);

Control Language Loading and Bundling

Bundled grammars load on first use through defaultLoader. Call setLoader() before highlighting when a bundle should expose only selected grammars or resolve custom language names. An unresolved language name renders as plain text.

import { setLoader } from '@speed-highlight/core';
setLoader(name => ({
  js: () => import('@speed-highlight/core/languages/js.js'),
  css: () => import('@speed-highlight/core/languages/css.js'),
  html: () => import('@speed-highlight/core/languages/html.js')
})[name]?.());

Full Tree-Shaking

tokenizeWith() receives grammars directly from the caller and does not use the language loader. Import every embedded grammar needed by the selected language. HTML uses CSS and JavaScript, and JavaScript uses JSDoc, TODO, and regex grammars for inner tokenization.

import { tokenizeWith } from '@speed-highlight/core/tokenize';
import {
  html,
  css,
  js,
  jsdoc,
  todo,
  regex
} from '@speed-highlight/core/languages';
tokenizeWith(
  sourceCode,
  html,
  (text, tokenType) => {
    console.log(tokenType, text);
  },
  {
    languages: {
      css,
      js,
      jsdoc,
      todo,
      regex
    }
  }
);

Available Themes

Browser themes use CSS files. The default and atom-dark themes also have JavaScript versions for ANSI output. Import one CSS theme in browser applications.

  • default
  • atom-dark
  • dark
  • github-dark
  • github-dim
  • github-light
  • visual-studio-dark
import '@speed-highlight/core/themes/github-dark.css';

Supported Language Classes

LanguageClass Name
Assemblyshj-lang-asm
Bashshj-lang-bash
Brainfuckshj-lang-bf
Cshj-lang-c
CSSshj-lang-css
CSVshj-lang-csv
Diffshj-lang-diff
Dockerfileshj-lang-docker
Gitshj-lang-git
Goshj-lang-go
HTMLshj-lang-html
HTTPshj-lang-http
INIshj-lang-ini
Javashj-lang-java
JavaScriptshj-lang-js
JSDocshj-lang-jsdoc
JSONshj-lang-json
LeanPub Markdownshj-lang-leanpub-md
Logshj-lang-log
Luashj-lang-lua
Makefileshj-lang-make
Markdownshj-lang-md
Perlshj-lang-pl
Plain textshj-lang-plain
Pythonshj-lang-py
Regular expressionsshj-lang-regex
Rustshj-lang-rs
SQLshj-lang-sql
TODO commentsshj-lang-todo
TOMLshj-lang-toml
TypeScriptshj-lang-ts
URIshj-lang-uri
XMLshj-lang-xml
YAMLshj-lang-yaml

Configuration Options

  • block (boolean): Uses block markup when set to true. highlightHTML() defaults to block output. highlightElement() chooses inline output for a code element and block output for other elements unless this value is set explicitly.
  • showLineNumbers (boolean): Displays a numbered gutter for block output. The default value is false.

API Methods

import {
  highlightAll,
  highlightElement,
  highlightHTML,
  highlightANSI,
  tokenize,
  setLoader,
  defaultLoader
} from '@speed-highlight/core';
// Highlight every element with a shj-lang-* class.
await highlightAll({
  showLineNumbers: true
});
// Highlight one DOM element.
await highlightElement(
  document.querySelector('#css-preview'),
  'css'
);
// Return highlighted HTML.
const html = await highlightHTML(
  'body { margin: 0; }',
  'css',
  { block: true }
);
// Return ANSI-colored text.
import terminalTheme
  from '@speed-highlight/core/themes/default.js';
const ansi = await highlightANSI(
  'console.log("Build finished");',
  'js',
  terminalTheme
);
// Process the token stream through the configured loader.
await tokenize(
  'const visible = true;',
  'js',
  (text, tokenType) => {
    console.log(tokenType, text);
  }
);
// Replace the language loader.
setLoader(name => defaultLoader(name));

Detection and Low-Level Tokenization APIs

import {
  detectLanguage
} from '@speed-highlight/core/detect';
import {
  tokenizeWith,
  tokenizer
} from '@speed-highlight/core/tokenize';
// Guess a language name or return "plain".
const detected = detectLanguage(sourceCode);
// Tokenize with grammars supplied by the caller.
tokenizeWith(
  sourceCode,
  grammar,
  (text, tokenType) => {
    console.log(tokenType, text);
  }
);
// Access the lower-level generator.
const iterator = tokenizer(
  sourceCode,
  grammar,
  (text, tokenType) => {
    console.log(tokenType, text);
  }
);

Custom Languages

A custom grammar is an array of matching rules. A rule can assign a token type, reuse a shared expansion such as str or num, or send a matched region through another grammar.

import { highlightHTML } from '@speed-highlight/core';
const paletteGrammar = [
  {
    match: /\b(primary|secondary|surface)\b/g,
    type: 'kwd'
  },
  {
    match: /#[0-9a-f]{6}\b/gi,
    type: 'num'
  },
  {
    expand: 'str'
  }
];
const highlightedPalette = await highlightHTML(
  'primary: "#635bff"',
  paletteGrammar
);

CSS Styling Hooks

Browser themes style the host element, display classes, line-number gutter, and shj-syn-* token classes. highlightElement() also writes the detected or assigned language to data-lang.

HookPurpose
shj-lang-*Identifies the grammar for a source element.
shj-blockMarks block output.
shj-inlineMarks inline output.
shj-numbersStyles the line-number gutter.
data-langStores the current language on a highlighted element.
shj-syn-kwdKeywords.
shj-syn-strStrings.
shj-syn-cmntComments.
shj-syn-numNumbers.
shj-syn-funcFunctions.
shj-syn-classClasses.
shj-syn-typeTypes.
shj-syn-varVariables.
shj-syn-boolBoolean values.
shj-syn-operOperators.
shj-syn-escEscape sequences.
shj-syn-errError tokens.
shj-syn-sectionSection tokens.
shj-syn-insertInserted text.
shj-syn-deletedDeleted text.

Custom Theme Example

Override the generated token classes in your stylesheet when the bundled themes do not match the site design.

[class*="shj-lang-"] {
  color: #f8f8f2;
  background: #282a36;
}
.shj-syn-kwd {
  color: #ff79c6;
}
.shj-syn-str,
.shj-syn-insert {
  color: #50fa7b;
}
.shj-syn-cmnt {
  color: #6272a4;
  font-style: italic;
}
.shj-numbers {
  color: #6272a4;
}

Alternatives:

Changelog:

v2.0.1 (08/25/2026)

  • Fixed Markdown headings, dash lists, and table separators.
  • Fixed Markdown inline code spans and one-character underlines.

v2.0.0 (08/14/2026)

  • Introduced highlightHTML() and highlightANSI().
  • Moved display mode into the block option.
  • Changed line numbers to opt-in through showLineNumbers.
  • Replaced loadLanguage() with loader controls and direct grammar input.
  • Merged terminal highlighting into the main package entry.
  • Introduced registry-free tokenization with tokenizeWith().

v1.2.24 (08/09/2026)

  • Bugfixes

v1.2.18 (08/01/2026)

  • Improve HTML regex for properties

You Might Be Interested In:


Leave a Reply