N Kaushik

How to do code syntax highlight in a gatsby site

November 08, 2020

This site is built using gatsby. I prefer markdown to write blogs and also to save notes. For this blog, I am writing all posts in markdown and gatsby converts them to static web pages.

Before writing this post, I didn’t have anything to highlight code snippets. It looked as like below :

gatsby syntax highlight

One more reason, I love gatsby because of its high range of plugins. Plugins are available for almost anything that you want. Previously I used wordpress but now I migrated all of them to gatsby.

Syntax highlight in gatsby websites:

I am using deckgo/gatsby-remark-highlight-code for syntax highlighting on this website. This is the github page for this plugin.

Installation requires only one npm command:

npm install --save gatsby-transformer-remark gatsby-remark-highlight-code @deckdeckgo/highlight-code

I am using gatsby-transformer-remark for parsing the markdown files. For adding styles to this plugin, you need to update your gatsby-config.js as below:

plugins: [
  {
    resolve: `gatsby-transformer-remark`,
    options: {
      plugins: [
        {
          resolve: `gatsby-remark-highlight-code`
        },
      ],
    },
  },
]

For gatsby-plugin-mdx, use this :

plugins: [
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [".mdx", ".md"],
        gatsbyRemarkPlugins: [
          {
            resolve: `gatsby-remark-highlight-code`,
          },
        ],
      },
    },
]

You can also give one terminal and theme option as below:

{
    resolve: `gatsby-remark-highlight-code`,
    options: {
        terminal: 'ubuntu',
        theme: 'blackboard'
    }
},

You can use carbon, ubuntu or none as terminal. There is a wide range of themes available. You can see and test them here.

Finally, import it in your index.js or any other page:

import { defineCustomElements as deckDeckGoHighlightElement } from '@deckdeckgo/highlight-code/dist/loader';
deckDeckGoHighlightElement();

That’s it. The above code now looks like :

gatsby code highlight


Subscribe to my Newsletter