🎨 Shiki and Prism Syntax Highlighting #
Here we see how you can set up SvelteKit Shiki syntax highlighting in your Svelte app. Shiki and Prism are both fantastic code syntax highlighters. Although Prism is currently more popular, recent projects like Astro are using Shiki as the default. Shiki has many themes built into the package and also supports TextMate themes, used by VS Code. While Prism probably offers easier customization, we will see here that adding line numbers and even applying individual line highlights are not too difficult with Shiki. An additional advantage of using Shiki is that it supports Svelte code highlighting out-of-the-box. We shall focus on Shiki in this post, but let me know if there is something you would like to see in Prism, and I will see what I can do.
🧱 What we’re Building #
We will build a single page of a SvelteKit app to show how you can use Shiki, SvelteKit and mdsvex. mdsvex uses PrismJS by default. However, it also supports bringing your own highlighter. We will use Shiki as the custom highlighter and add line numbers. As well as line numbers, we will add additional highlighting to certain specified lines. Typically, you would want to do this to make a line, which you later refer to, stand out. Finally, we will improve the accessibility of the output code blocks with a further tweak. If that sounds like what you were looking for, then let’s get cracking!
⚙️ SvelteKit Shiki Syntax Highlighting: Setup #
We’ll start with a new SvelteKit project. Spin it up now from the Terminal:
Choose a Skeleton project from the CLI init tool. We will use Type-checked JavaScript in the demo code, but feel free to pick TypeScript
or None
if you prefer. For the other options, select what you are happiest with!
We will use a couple of packages in this project, let’s add them now:
That’s the initial prep. We have a touch more setup to do for mdsvex, and once that’s done, the plan of action is to move straight on to creating an initial code highlight function. After that, we’ll create some Markdown code to test on and some styling. Finally, we level up, making the highlight function more robust and accessible. Next up is the mdsvex config.
🔧 mdsvex Configuration #
First, create an mdsvex config file, mdsvex.config.mjs
in the project
root directory:
We will create the highlighter
function imported in line 2
in the next section. In lines 8
– 11
we see how we let mdsvex know about our
custom highlighter. We will see it is a function, which takes three arguments: code
, language
and meta
. language
is the language of the code block, while meta
is the extra parameters
we can specify in a fenced Markdown code block. As an example, we will later add a fenced code block,
which looks like this:
So here, the language is Svelte and the code is everything between the first and last line. {5-7,10-11}
is our on custom syntax, the meta
, which we will parse in the highlighter
function. You can add more bells and whistles if you build on the code for this project, here though
we will just use this as a way to pass in the lines we want to style differently to add additional
highlighting.
svelte.config.js
#
Finally, finish the config step by updating svelte.config.js
in the
project root directory to include our mdsvex config:
👋🏽 highlighter
: Initial Version #
We will keep the code below but build on it as we go along. For now create a src/lib/utilities
directory and add a codeHighlighter.mjs
file there with the following
content:
We are using the github-dark
theme here. If you use a different theme,
be sure to run an accessibility checker on your output to make sure the contrast ratios are good. You
can see a list of all inbuilt Shiki themes on the Shiki project GitHub page .
With that in place, why don’t we create some code to highlight?
🖥 Code #
mdsvex lets us write source files in Markdown. We just need to register the file extensions we
plan to use for Markdown. We did this in line 7
of mdsvex.config.mjs
as well as line 7
of svelte.config.js
. Here is some Rust and JavaScript code we can test on. Rename src/lib/routes/+page.svelte
to +page.svelte.md
and replace the content:
When you paste in these code blocks, make sure the lines with backticks, which start and end the
fenced code blocks are not indented. If you open up the page in a browser, you should now see some
highlighted code. We will add more styling later. If this does not work for you, try stopping your
dev server, running rm -r .svelte-kit
and then restarting the dev server.
Next try adding some Svelte code to the bottom of the same file (this is taken from the Svelte demo code):
You should get an error because Vite is parsing the code in the Svelte code block we just added.
We can prevent this by escaping the HTML generated by the highlighter
function. We will address this next.
🏃🏽 highlighter
Escaping Generated HTML Code #
We can create an escapeHtml
function, which replaces some characters
with their HTML entity equivalents. Specifically, we will replace “{
”, “}
” and “`
”. Add this function to src/lib/utilities/codeHighlighter.mjs
:
Then use the function in line 25
:
You might need to restart the dev server for this to take effect. The browser will now show the
Svelte code without errors. We are not yet done with the highlighter
but will look at some styling before returning to it.
💄 SvelteKit Shiki Syntax Highlighting: Styling #
First, create a global CSS file. Make a new directory src/lib/styles/
and in it create styles.css
with the following content:
Then we create a layout file, which mdsvex will use for all pages it processes. Make a src/lib/components
directory and add a MarkdownLayout.svelte
file:
The final missing piece here is to use the new layout, uncomment line 11
in mdsvex.config.mjs
:
You might need to restart your dev server once more for any changes to take effect. The code
blocks should look a lot nicer now. You will also notice we now have line numbers. These come from
the CSS in lines 22
– 25
& 90
– 99
in
the src/lib/styles/styles.css
file.
🤗 Accessibility Improvement #
Exploring the HTML from the first block, we can see it looks something like this:
For long lines, the <pre>
block will be horizontally scrollable.
For accessibility, it will need to be focusable. This is possible by adding a tabindex
attribute to the element. At the time of writing, it is not possible to do this within Shiki, though
there is a pull request to modify the API . Instead, we will just update the output HTML using node-html-parser
. Add this new function to src/lib/utilities/codeHighlighter.mjs
:
Then use the function in line 42
:
⭐ Using SvelteKit with Shiki: Extra Line Highlighting #
We might want to add additional highlighting to particular lines. One way to do this with Shiki is
to add a new class to certain lines. This is possible using the transformers
field in the Shiki codeToHtml
, with a transform function from @shikijs/transformers
function call options. Here is the final version of the highlighter
function:
So here we check if there is range meta passed into the highlighter
. When we do have meta, we use tje transformerMetHighlight function to add a highlighted
class to matching lines. We added styling for this earlier in src/styles/styles.css
(lines 36
– 42
), though we did not mention it at the time.
Restart your dev server once more if the changes do not appear in the browser. Try adding highlight meta to the other code blocks or changing the highlight ranges for the Svelte block. Do not include any spaces in the ranges you specify.
🗳 Poll #
💯 SvelteKit Shiki Syntax Highlighting: Test #
It should all be working now. We focussed on getting through the demo, rather than explaining every detail. Because of that, please do let me know if there is some part, which needs some clarification. Also, remember to run accessibility contrast checks, especially if you have changed the themes.
🙌🏽 SvelteKit Shiki Syntax Highlighting: Wrapup #
In this post we looked at:
- how to add Shiki syntax highlighting in SvelteKit, including line numbers and extra highlighting styles for some lines,
- generating your own code highlighter with mdsvex,
- how to manipulate the output Shiki HTML to make the result more accessible.
I do hope there is at least one thing in this article, which you can use in your work or a side project. Also, let me know if you feel more explanation of the config is needed.
This post is related to a question I got on Twitter on adding line numbers to code blocks, so do reach out if you have questions I might be able to write a post on. I also create short videos focussed on a particular topic.
You can see the full SvelteKit code for this project on the Rodney Lab Git Hub repo . If you run into any issues, you can drop a comment below as well as reach out for a chat on Element . Also, Twitter @mention if you have suggestions for improvements or questions.
🏁 SvelteKit Shiki Syntax Highlighting: Summary #
Does Shiki work with mdsvex? #
- Although out-of-the-box, mdsvex uses PrismJS for code highlighting, you can define a custom highlighter using Shiki (or even your own hand-rolled highlighter). To do this, just pass a highlighter function to the mdsvex configuration. The highlighter function takes three arguments, the code itself, the coding language of the code and some optional meta. The meta will be helpful if, for example, you want to add extra highlighting to certain lines.
How can you make a scrolling code fragment focusable? #
- Making scrolling elements focusable helps users navigating the site by keyboard scroll those elements. For that reason, it is important these elements are focusable for accessibility reasons. To make an element scrollable, add a tabindex attribute. Set the value of this element to a non-negative value. Negative tabindex values are only used when the element should not be focusable. For positive tabindex values, the order of the values sets the sequence in which users will tab through the elements. That said, you should arrange elements in a logical order and set tabindex to 0 for all focusable element whenever possible.
How can you add line numbers to Shiki highlighted code? #
- At the time of writing, Shiki does not have an API for adding line numbers, however, it is fairly easy to do so with CSS. We have seen you can use CSS counters to add line numbers as a pseudo-element at the start of each line.
🙏🏽 Feedback #
If you have found this video useful, see the links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.
Just dropped a new blog post showing you how to use mdsvex with Shiki syntax highlighting in your ❤️ Svelte blog.
— Rodney (@askRodney) April 27, 2022
You see how to add line numbers and also extra classes to code particular lines for alternative highlighting.
I hope you find it useful!
https://t.co/Iko9hZuH2l
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimization among other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.