Setting up Shiki on Next.jsPublished See discussion on Twitter
I recently updated how I handle syntax highlighting within code blocks on my
personal site here. After my recent refactor a few months ago, I had adopted
highlight.js originally but then only recently realized that it still doesn't
support JSX/TSX syntax highlighting.
I did some googling around, almost went down the path of using Prism.js as well,
and then remembered that
shiki exists and decided
to give it a try.
Originally, I thought it was going to be pretty easy, or at least it was easy to implement for local development within my React Server Component setup for my blog. It was only when I went to deploy it that it started to break.
I ran into the following error and was a bit confused on what it meant:
It turns out that by default, Next.js doesn't bundle in
shiki, which means
there's a raw
require or dynamic import for the text grammars and the themes.
After stumbling across a few different issues, each with different ways to resolve the problem I was running into, I found the following solution:
- Import the themes and grammars that are needed manually
- Pass them directly into the
Here's a complete example of my current CodeBlock component:
For some reason, shiki's TypeScript types don't seem to like me passing in the themes or the grammars manually, so I opted to ts-ignore those errors for the time being 🙂.
Hopefully this helps others that might run into the same issue!