I recently implemented PrismJS for code highlighting in GatsbyJS . Since there weren’t that many posts to do a quick installation here is how I did it.
Install PrismJS
First, install PrismJS and it’s Gatsby plugins:
npm install --save gatsby-transformer-remark gatsby-remark-prismjs prismjs
This will make sure that you have all the plugins needed. Next, go to your gatsby-config.js
and put the following code after your declaration of gatsby-transformer-remark
since this is a plugin it has to go in the plugins section like this:
// gatsby-config.js
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-prismjs`,
options: {
aliases:{sh: "bash", js:"javascript"},
showLineNumbers: true,
}
}],
},
Choose a PrismJS Theme
After that you have to include the PrismJS theme you like in your Gatsby-browser.js
file and also include the line numbers like that
// gatsby-browser.js
require("prismjs/themes/prism-tomorrow.css");
require("prismjs/plugins/line-numbers/prism-line-numbers.css");
Optional: Atom Editor Style
Since I didn’t really like the default themes that PrismJS comes with I looked for a one that I liked more. And I found my beloved Atom Editor Style in the additional themes that are available on GitHub. To include it install prism-themes
with npm.
npm i prism-themes
And include change your gatsby-browser.js
to this:
// gatsby-browser.js
require("prism-themes/themes/prism-atom-dark.css");
require("prismjs/plugins/line-numbers/prism-line-numbers.css");
Change your CSS
Because of the line numbers, there have to be changes in your CSS. Mine is in /components/layout.css
. There you have to add the following lines to get everything in order:
.gatsby-highlight {
background-color: #1d1f21;
border-radius: 0.3em;
margin: 0.5em 0;
padding: 1em;
overflow: auto;
}
.gatsby-highlight pre[class*="language-"].line-numbers {
padding: 0;
padding-left: 2.8em;
overflow: initial;
}
That’s it. You just implemented PrismJS in GatsbyJS to highlight your code blocks with the Atom Editor Style.
PS: I also updated my GatsbyJS starter to use PrismJS.
Thank you for reading,
Niklas
This post was first posted on my blog: niklasmtj.de
Photo by Émile Perron on Unsplash
Top comments (1)
Hi Niklas,
This is actually a great tutorial and I followed it for a new theme I am making for Gatsby. Thank you very much.
I am currently banging my head trying to implement gatsbyjs.org/packages/gatsby-remar... .
How would you feel adding to your tutorial and adding this? I will forever be grateful and anyone reading my code will see a link to this post!
EDIT:
I forgot to mention I am using MDX. And I found this example in GitHub - github.com/iamskok/gatsby-mdx-rema... - but their steps are not working for me :(
EDIT EDIT:
Apparently this will not work with MDX. Here is my branch if you are interested: github.com/davidkartuzinski/gatsby...
And here is an issue comment: github.com/iamskok/gatsby-remark-c..., mine: github.com/iamskok/gatsby-remark-c...