Implement PrismJS in GatsbyJS
2 min read
376 words
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