💾 Archived View for wilw.capsule.town › log › 2021-07-28-gatsby-syntax-highlighting.gmi captured on 2023-07-10 at 13:53:52. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2023-04-19)

-=-=-=-=-=-=-

🏡 Home

Back to gemlog

Code syntax highlighting in Gatsby

Posted on 28 July 2021

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 [1] and write your blog posts or pages in markdown format, then adding syntax highlighting is super easy.

1

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

2

3

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 [4] from Prism. To enable one, simply add an entry to your `gatsby-browser.js` file. For example:

4

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:

<pre>

  console.log('Hello, world');

</pre>

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

5

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 [6].

6

Reply via email

Back to gemlog