A lightweight <code-highlighter> custom element that provides syntax highlighting without DOM mutation, using the CSS Custom Highlight API
- No DOM mutation for highlighting (no
<span>injection) - Uses Prism.js's tokenizer, but lets you decide how to import it
- Works as a read-only viewer or simple editor
- Minimal, only 50 lines of JavaScript
- Requires a modern browser with CSS Custom Highlight API support
- Prism must be loaded before
<code-highlighter>runs
<code-highlighter
language="clojure"
spellcheck="false"
>
(defn greet [name] (str "Hello, " name))
</code-highlighter><code-highlighter
language="clojure"
contenteditable="plaintext-only"
spellcheck="false"
oninput="this.highlight()"
>
(defn greet [name] (str "Hello, " name))
</code-highlighter>Note: Consider debouncing calls to highlight() to avoid re-tokenizing on every keystroke
Recompute syntax highlighting
<code-highlighter oninput="this.highlight()"></code-highlighter>- Add Prism core and any languages you need
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.30.0/components/prism-core.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.30.0/components/prism-clojure.min.js"></script>- Add
<code-highlighter>
<script type="module"
src="https://cdn.jsdelivr.net/npm/@thiago.oak/code-highlighter@latest/code-highlighter.js"></script>- Add a theme
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@thiago.oak/code-highlighter@latest/prettylights.css"/>Highlight colors are defined with ::highlight() selectors. Your theme sets them