Will's avatar

⬅️ See more posts

Code syntax highlighting in Gatsby

28 July 2021 (2 minute read)

🔮 This post is also available via Gemini.

100daystooffload technology javascript react

💯 100 Days to Offload

This article is one of a series of posts I have written for the 100 Days to Offload challenge. Disclaimer: The challenge focuses on writing frequency rather than quality, and so posts may not always be fully planned out!

View other posts in this series.

Providing code snippets on your website or blog can be a great way to convey meaning for technical concepts.

Using the HTML pre tag can help provide structure to your listings, in terms of spacing and indentation, but highlighting keywords - as most people do in their code text editors - also vastly helps improve readability.

For example, consider the below JavaScript snippet.

class Greeter {
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

const greeter = new Greeter();
greeter.greet('Will');

The exact same listing is displayed below with some simple syntax highlighting. The structure and meaning of the code becomes much easier to understand.

class Greeter {
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

const greeter = new Greeter();
greeter.greet('Will');

If you build your website with GatsbyJS and write your blog posts or pages in markdown format, then adding syntax highlighting is super easy.

PrismJS is a well-established library for achieving syntax highlighting on any website. Luckily, there is also a Gatsby plugin for Prism which makes it much easier to get started in Gatsby websites.

First of all, add the required dependencies to your project:

yarn add gatsby-transformer-remark gatsby-remark-prismjs prismjs

Next, add an entry to the plugins array in your gatsby-config.js file to use the plugin. For example, the below is what I use.

  ...
  plugins: [
    ...
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-prismjs',
            options: {
              classPrefix: 'language-',
              showLineNumbers: true,
              noInlineHighlight: false,
            }
          }
        ]
      },
    },
  ],
  ...

Finally, you’ll need to choose a theme. There are a number of official ones available from Prism. To enable one, simply add an entry to your gatsby-browser.js file. For example:

require('prismjs/themes/prism-solarizedlight.css');

That’s it - now in your markdown you can add a block of code to syntax-highlight as follows:

You can change the javascript part to a supported language you are using, and Prism will syntax-highlight accordingly.

Extra configuration

If you want to add extra features - such as line numbers - or if you run into issues, I recommend checking out the documentation for the plugin.

✉️ You can reply to this post via email.

📲 Subscribe to updates

If you would like to read more posts like this, then you can subscribe via RSS.