Customizing Markdown Syntax Highlighting in Astro with Shiki

I’ve created this Blog using Astro, a modern front-end framework for building websites that deliver outstanding performance by not including client javascript by default, plus some other benefits related to SEO (Search Engine Optimization) compared to other frameworks. Every blog post is created using Markdown, a very convenient choice, and among the advantages, this makes it easy to create code blocks natively. One thing that I immediately noticed while starting to add code blocks to my first blog post, though, was that the rendering of the code was not particularly fancy when compared to the ones I already saw on other websites. I already heard about the existence of Prism.js, a lightweight and extensible syntax highlighter. Still, during my search, I discovered that Astro uses Shiki as its default syntax highlighter, so I’ve decided to go for it.

To customize the aspect of your code blocks, you can simply modify the ‘markdown’ key of your ’astro.config.mjs’ file like this:

markdown: {
    shikiConfig: {
      theme: 'dark-plus',      // Set the theme for your code blocks.
      langs: ['javascript'],   // Extend the supported languages, if needed.
      wrap: true,              // Avoid horizontal scrolling with word wrapping.
    },
}
  • theme: Dictate the appearance of your code blocks. We’re using the ‘dark-plus’ theme here, but numerous others are available on Shiki’s Githubpage.
  • langs: Specify any additional programming languages you want to highlight. Although many, like ‘javascript’, are already supported, you can add more to suit your needs.
  • wrap: Enable word wrapping for more readable code without the horizontal scroll.

I also noticed that you can further tweak the aspect of your code blocks using CSS to add a final touch. For example, to add some padding and margin, you could add this to your global css file:

pre {
  margin: 0.5rem 0 16px;
  padding: 0.8rem 1rem 0.9rem;
}

Note that pre is used here since when you write multi-line code blocks (surrounded by triple backticks), Markdown typically generates a combination of ‘pre’ and ‘code’ elements.

To summarize, with just a few lines, your Astro project’s Markdown content becomes beautiful and more reader-friendly.

Happy coding!