For the first time since 2023 I'm available again for new projects. If you need a developer with 25 years of experience building websites and iOS apps, check out the Hire me page.

Announcing Moon, a new HTML syntax highlighter for Swift projects

Hero image

My website is built using Saga, a static site generator written in Swift. Overall it’s a great experience, but there was always one problem: there are no HTML syntax highlighters for Swift. To get around this I used the Prism.js JavaScript library in the browser. It finds all the code blocks on the web page and automatically highlights them.

This works fine, but it requires every visitor to load quite a bit of JavaScript just for syntax highlighting. This is something that really should be done server side, without the browser having to download any JavaScript files.

I looked at a few existing Swift packages:

I was thinking about using Claude Code to port Prism.js to Swift, but translating the language definitions from JavaScript regexes to Swift would be a nightmare, and not something I’d want to maintain going forward.

Instead, I was inspired by Highlightr. If I could use JavaScriptCore to run the real Prism.js library, but “server-side” rather than in the browser, it would solve all my problems with very little complexity. The biggest issue was the fact that JavaScriptCore is Apple-only, it doesn’t work on Linux. Luckily I found JXKit which offers a cross-platform module for running JavaScript in Swift.

All the pieces came together quite quickly after that, and the result is Moon, a brand new Swift library using Prism.js “server-side”. You give it an HTML string with <code> blocks, and it returns an HTML string with those blocks now properly highlighted. Prism.js supports 290+ languages, with even more available as third-party plugins.

This website now uses Moon to highlight all code blocks, speeding up page load for everyone by no longer needing to load Prism.js in the browser.

Written by

Avatar

Kevin Renskers

Related articles

› See all articles