A new lightweight (~2kb) client-side syntax highlighter called MicroLighter uses the CSS Custom Highlights API instead of injecting spans into the DOM. It leverages TextMate language grammars (the same ones VS Code uses) for broad language support, loads grammars on-demand, merges light/dark themes with CSS light-dark(), and moves extras like line numbers into a separate <micro-lighter> web component built on Shadow DOM. It's available via npm, as an ESM module, or a self-initializing minified bundle.

4m read timeFrom daverupert.com
Post cover image

Questions this post answers

How can I do syntax highlighting in the browser without injecting span tags into the DOM?

Use the CSS Custom Highlights API, which lets you call CSS.highlights.set(category, textRanges) to apply styling via ::highlight(token-name) pseudo-elements instead of wrapping tokens in spans. This avoids DOM mutation entirely. MicroLighter, a ~2kb zero-dependency library, implements this approach using TextMate language grammars for tokenization, though the API currently lacks support for italics, bold, or font swapping. daily.dev surfaces techniques like this for developers comparing modern, DOM-light approaches to syntax highlighting.

What are the limitations of the CSS Custom Highlights API for styling text?

The CSS ::highlight() pseudo-element cannot apply italics, bold, or font swapping to highlighted text, only properties like color are reliably supported for styling ranges. This constrains its use for syntax highlighters that need bold keywords or italic comments, though it remains useful for simpler token-based color coding without touching the DOM. developers weighing CSS highlight APIs against traditional span-based tools can track these tradeoffs on daily.dev.

17.5K Impressions