MW

Gatsby/Ghost Syntax Highlighting with Prism.js


Short written guide on how to add syntax highlighting in gatsby for your ghost blog.

Setting up syntax highlighting with Ghost blog is not too complicated, because it is handled client side with the prism.js library. Getting it to work with Gatsby is a bit more complicated and not yet fully supported out of the box.

There are plugins for Gatsby that implement prism.js, like gatsby-remark-prismjs, but this would require that your post content is available in Gatsby as Markdown file before you build your project. Instead the content of a post/page is set as inner HTML of the Content component. Therefore the gatsby-remark-prismjs plugin won't work. I found hints to a working solution in a discussion on github.

Syntax highlighting in Gatsby with a Ghost Backend

  1. install prismjs
npm install prismjs

2. Add a theme for prismjs to gatsby-browser.js

...
require("prismjs/themes/prism-coy.css")
...

3. Implement syntax highlighting in your content component. Include prism.js and the plugins you want in your file (more about plugins can be found in the prism.js documentation). Add Prism.highlightAll() to your componentDidMount function. This will trigger the syntax highlighting client side after loading your component. This requires that you use a class component to display your content. If you also want to have line numbers, every <pre> element before a <code> element needs to be of class line-numbers. I use a very hacky solution, where I use a RegEx to replace all occurances of <pre> with <pre class="line-numbers">.

... imports
import Prism from 'prismjs'
import "prismjs/plugins/line-numbers/prism-line-numbers.js"

class Post extends React.Component {

  constructor(props){
      super(props)
  		... constructor
        this.post.html = this.post.html.replace(new RegExp("<pre><code", "g"), '<pre class="line-numbers"><code')
    }

    componentDidMount(){
      Prism.highlightAll()
    }

    render(){
      return (
      		<PostStyled dangerouslySetInnerHTML= {{ __html: this.post.html }}/>
        )}
}

After completing these steps your posts should now have syntax highlighting with line numbers enabled.

...
Last Update:

Other.

Blog.

Ghost

Gatsby

Latest.

View Project

Setting up Ghost and Gatsby


In this post I am going to guide you through the process of setting up Ghost and Gatsby.

Contact.

Markus Wallinger


I am currently finishing my Master Thesis at the Vienna University of Technology. One the side I work as a freelance software developer, based in Vienna and Tyrol.

Discuss.

Markus Wallinger