• s
  • i
  • m
  • o
  • n
  • s
  • t
  • e
  • n
  • b
  • a
  • æ
  • e
  • k
⟻ Back
Gatsbyjs

How to add code syntax highlighting to your markdown driven gatsby blog

So you've made your gatsby markdown-driven blog. Now you want to dazzle your coder audience with beautifully highlighted code. Here is how you do it in less than 5 minutes.

I recently switched my personal site over from "vanilla" react, to this lightning fast gatsbyjs site. I wouldn't want to start blogging about code without being able to show off code snippets in the best way possible; with proper syntax highlighting. I was blown away by how easily I was able to accomplish this with the strength of the gatsby plugin library.

Supposing you already have a markdown blog running using gatsby-transformer-remark on your gatsby site, you'll only need to install a few more plugins for this to work.

npm install --save prismjs gatsby-remark-prismjs

After you've installed these plugins, let's add them to our gatsby-config.js

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

We're almost there - now we just need to import some styling to make it look good

Styling and themes

Prismjs comes with some built-in themes, which you can add directly from the prismjs npm module.

This is done by simply importing it in our gatsby-browser.js file:

// gatsby-browser.js
...
require("prismjs/themes/prism.css")
...

Aaaaand... That's it! I told you it would be quick. My blog is a living example of what you can expect.

How do I actually use it in my markdown?

Now, all you have to do to get the sweet highlighting, is to add some code blocks to your markdown:
A fenced code block is created by adding three backticks () or three tildes (~~~) before and after your code.
To get syntax highlighting with prismjs, you add the language right after the first three backticks:

~~~javascript
_.memoize = function(func, hasher) {
    var memoize = function(key) {
        var cache = memoize.cache;
        var address = '' + (hasher ? hasher.apply(this, arguments) : key);
        if (!has(cache, address)) cache[address] = func.apply(this, arguments);
        return cache[address];
    };
    memoize.cache = {};
    return memoize;
};
~~~

Which will output...

_.memoize = function(func, hasher) {
  var memoize = function(key) {
    var cache = memoize.cache
    var address = "" + (hasher ? hasher.apply(this, arguments) : key)
    if (!has(cache, address)) cache[address] = func.apply(this, arguments)
    return cache[address]
  }
  memoize.cache = {}
  return memoize
}

Beautiful!