Code blocks are a great way to explain concepts to your readers, and you'll want to make them as easy to understand as possible. In this post I'll be covering some of the ways you can improve the code blocks on your Gatsby blog.
Syntax highlighting changes the colour of parts of your code to make it more readable. It’s something you’re used to having in your code editor, but you can have it in your code blocks too!
Syntax highlighting is available with the gatsby-remark-prismjs plugin. You may already have it installed if you started your blog using one of Gatsby’s default templates.
To use syntax highlighting, you’ll need to specify the language of your code block:
And you will get beautiful syntax highlighting like so:
You can see the full list of supported languages over on the PrismJS website.
To save your readers having to manually copy code, you can provide them with a “copy code” button using gatsby-remark-code-buttons.
This will work great for anyone who is using Markdown to power their Gatsby blog.
Unfortunately for MDX users there isn’t a plugin available so you will have to hack your own solution. My blog is powered with MDX, so I may have to look into how to do this in the future.
Sometimes you'll want the reader to focus on a specific line of code, but still show the code around it. You can create this focus by using line highlighting.
This doesn’t need another plugin, as gatsby-remark-prismjs provides this out of the box.
If you want to highlight a specific line, you can add a
// highlight-line comment to the end of it:
As an alternative to line highlighting, you can also show code diffs using plus and minus signs.
With some CSS, you’ll be able to make the “+” line green, and the “-“ line red. The one downside here is that you will lose any language-specific syntax highlighting.
I personally haven't needed to use this one yet, but I could see it being useful in some scenarios.
Sometimes you’ll want to show code blocks from different files. In this scenario, it’s helpful to your reader if you show the title of the current file. gatsby-remark-code-titles is a plugin that will handle this for you.
You can specify the title on the first line of your code block like this:
With its massive ecosystem of plugins, Gatsby makes it simple to add these improvements to your code blocks.
Thanks for reading!