Sunday, January 24, 2021
better nuxt content code highlighting
This article was written over 2 years ago. Information and code examples may be out of date.
TL;DR
You can use as your highlighter. If you do a quick regex replace, you can even support dark mode! You can look at this blog for working code:
- The @nuxt/content configuration and hacks
- The shiki theme for base16 css variables
- The base16 css variables
A longer story
Today I was working on dark mode support for this blog and I noticed that the code blocks don't line up with my editor. This bothered me more than it probably should have, so I decided to dig into it.
Not shortly down the line, I found shiki. This project powers the code highlighting on the VS Code website, and the TypeScript website, so you know it means business.
Integration with nuxt is pretty simple. There is even an example in the docs. What was not included was how to integrate this with tailwind and nuxt color mode. So I took a stab. The first two ideas did not work out so well, but I finally found a simple way of doing it.
First idea
Looking at the shiki theme files it's pretty easy to see the colors. So my first idea was pretty simple. Replace the colors with CSS variables. Sadly this attempt ended pretty quickly. Turns out that shiki will try to parse those values into hex codes, error out, and just return .
Second idea
Alright, so that didn't work. What if we could change out how it parses the color codes? Instead of using the function, I tried out the function. This basically lets you write your own output from all of the code tokens shiki makes. It's a really cool feature that lets you do crazy things, like output code blocks to svgs instead of html. Sadly, it ended up with the same result because color parsing happens before either of those two functions. Whoops.
Success
Finally I went back to the drawing board. I obviously needed to feed in hex color codes. At this point I already knew I wanted to use the base16 color setup for my code blocks. The interesting thing about that setup, there are only 16 codes... So instead of writing out my colors like , I just did . Not seeing it yet? How about to . Pretty cheeky eh? Now I just needed to add a simple regex, and tada, CSS variables for colors!
And a pretty basic file:
I won't post the whole shiki theme here, but it's up on GitHub if you want to see it.
Click the lightbulb in the footer to see the final product!