SvelteKit Shiki Syntax Highlighting: Markdown Codeblocks

This page summarizes the projects mentioned and recommended in the original post on dev.to

Our great sponsors
  • SurveyJS - Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App
  • WorkOS - The modern identity platform for B2B SaaS
  • InfluxDB - Power Real-Time Data Analytics at Scale
  • shiki

    A beautiful yet powerful syntax highlighter

    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/utilitties/codeHighlighter.mjs: /** * @param html {string} - code to highlight * @returns {string} - highlighted html */ function makeFocussable(html) { const root = parse(html); root.querySelector('pre').setAttribute('tabIndex', '0'); return root.toString(); } Enter fullscreen mode Exit fullscreen mode Then use the function in line 42: async function highlighter(code, lang, meta) { const shikiHighlighter = await getHighlighter({ theme: THEME, }); let html = shikiHighlighter.codeToHtml(code, { lang, }); html = makeFocussable(html); return escapeHtml(html); } Enter fullscreen mode Exit fullscreen mode ⭐ 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 lineOptions field in the Shiki codeToHtml function call options. We just need to pass in an array of objects representing lines we want to add the class to. This array’s elements include the class we want to add to the line. Although the class can be different for each line, that’s a little more than we need here. Here is the final version of the highlighter function: /** * @param code {string} - code to highlight * @param lang {string} - code language * @param meta {string} - code meta * @returns {string} - highlighted html */ async function highlighter(code, lang, meta) { const shikiHighlighter = await getHighlighter({ theme: THEME, }); let html; if (!meta) { html = shikiHighlighter.codeToHtml(code, { lang, }); } else { const highlightMeta = /{([\d,-]+)}/.exec(meta)[1]; const highlightLines = rangeParser(highlightMeta); html = shikiHighlighter.codeToHtml(code, { lang, lineOptions: highlightLines.map((element) => ({ line: element, // line number classes: ['highlight-line'], })), }); } html = makeFocussable(html); return escapeHtml(html); } export default highlighter; Enter fullscreen mode Exit fullscreen mode So here we check if there is range meta passed into the highlighter. When we do have meta, we parse that into an array of individual line numbers which need highlighting in the rangeParser function which we will add in a moment. For each line we need to highlight, we add the highlight-line class. We added styling for this earlier in src/styles/styles.css (lines 36– 42), though we did not mention it at the time. Moving on add this code for range parsing to the same codeHighligher.mjs file: import { parse } from 'node-html-parser'; import { getHighlighter } from 'shiki'; Enter fullscreen mode Exit fullscreen mode Then: /** * Returns array of line numbers to be highlghted * @param {string} rangeString - range string to be parsed (e.g. {1,3-5,8}) * @returns {number[]} */ function rangeParser(rangeString) { const result = []; const ranges = rangeString.split(','); ranges.forEach((element) => { if (element.indexOf('-') === -1) { result.push(parseInt(element, 10)); } else { const limits = element.split('-'); const start = parseInt(limits[0], 10); const end = parseInt(limits[1], 10); for (let i = start; i <= end; i += 1) { result.push(i); } } }); return result; } Enter fullscreen mode Exit fullscreen mode 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. 💯 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. 🙏🏽 Feedback If you have found this video useful, see 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. 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 Optimisation among other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.

  • sveltekit-shiki-code-highlighting

    SvelteKit Shiki syntax highlighting: use any VSCode colour theme to accessibly syntax highlight code on your SvelteKit app with line numbers.

    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.

  • SurveyJS

    Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.

NOTE: The number of mentions on this list indicates mentions on common posts plus user suggested alternatives. Hence, a higher number means a more popular project.

Suggest a related project

Related posts