Alk3my

Adding Prism JS for better syntax highlighting of code blocks in Gatsby

November 02, 2019

Prism JS allows for language-specific highlighting and a variety of out of the box styles for code blocks.

As with most Gatsby additions / plugins it's very easy to add. You need gatsby-transformer-remark installed already so refer to my previous posts if you haven't done those steps (assuming you're using Markdown too). After that just run the install command.

npm install --save gatsby-remark-prismjs prismjs

Edit your gatsby-config.js file again and add in gatsby-remark-prismjs as below.

...
  plugins: [
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-remark-prismjs`,
        ],
      },
    },
...

Go and try / choose an appropriate style for your website from the prism themes or make your own if you're keen. Add the stylesheet reference to your gatsby-browser.js file.

import "prismjs/themes/prism-coy.css";

That's it, enjoy the syntax highlighting, just add the language of the code block at the start. e.g

```javascript
some code {
}
```

There's a huge number of languages supported so check them all out.