⬅️ Back to blog

Code syntax highlighting in Gatsby

28 July 2021

🏷️ 100daystooffload 🏷️ technology 🏷️ javascript 🏷️ react

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.