Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

FidelVe
FidelVe

Posted on

     

The definitive guide for using PrismJs in Gatsby

wisdom of the ancients

wisdom of the ancients by xkcd

Learning to use a new technology has been in my experience, a process of spending days searching for information to piece together a puzzle of which you don't have the entire picture yet.

A process that is at the same time rewarding and frustrating, it has become a new experience that I just have to get used to while walking the path of a self-taught developer.

The most recent time I walked this path, was when I decided to remake my personal website usingGatsby and upon watching a lot of blogs and sites with really cool and styled block codes with syntax highlighting, I thought that it would be good to use it on my site.

There are many libraries for syntax highlighting, but the one that seems to be the most used and preferred isPrism, so I decided to not spend too much time searching the pros and cons of all of them and givePrism a try, I would be happy to see your opinions on other libraries in the comments.

The main thing that you need to take into account

If you are in the process of porting (or creating from scratch) your website or blog toGatsby, and wanted to usePrism for code highlighting, the first thing that you need to decide is whether you're going to be using markdown files or not, because the process is different depending on this decision.

The need for using markdown files will depend on the type of website you are creating, but basically, if you are creating ablog orblog-like type of website, in the end usingMarkdown to source the content to your site is the most efficient way to go. If this is your case, the process will involve installing and configuring a couple of gatsby plugins (gatsby-transformer-remark andgatsby-remark-prismjs), installing thePrism npm package and querying for theMarkdown files (or snippets) withGraphQL.

On the other hand, if you are creating any other type of website, with a more complex design,Markdown won't give you enough flexibility to apply things like collapsible containers, carousels, etc. In this case, you just need to getPrism working inReact while using a custom.babelrc configuration file.

I created a blankGatsby project to use for both examples, you can download ithere, or create it from the console using the following format.

gatsby new <project-name> https://github.com/FidelVe/gatsby-blank-starter
Enter fullscreen modeExit fullscreen mode

In case you haven't installGatsby yet, run the following command first:

npm i-g gatsby-cli
Enter fullscreen modeExit fullscreen mode

Gatsby, React and PrismJs without remark

The first scenario that I will be explained is usingPrism without markdown files. This scenario is basically usingPrism insideReact in a way thatGatsby can process without any problems.

Lets first create a new gatsby project.

gatsby new gatsby-prism https://github.com/FidelVe/gatsby-blank-starter
Enter fullscreen modeExit fullscreen mode

Try running thegatsby develop server and you will see the following page with the default<code> style.

before prism

The first thing to do is install the npmPrism package:

npminstall--save prismjs
Enter fullscreen modeExit fullscreen mode

Now we are going to installbabel-plugin-prismjs, thisplugin allows us to configure and customizePrism by usingBabel.

npminstall--save babel-plugin-prismjs
Enter fullscreen modeExit fullscreen mode

To use this plugin we need to create a.babelrc file and put our configurations in it.Gatsby ships with a default.babelrc file, in order to create our own file and modify it we need to install thebabel-preset-gatsby preset and add it to our new.babelrc file.

npminstall--save babel-preset-gatsby
Enter fullscreen modeExit fullscreen mode

At this point, we have already installed everything we need so let's start with the configurations.

First, create a new file at the root of the project and call it.babelrc. Inside this file, we can customizePrism, in my case this is the content of the.babelrc file.

{"presets":["babel-preset-gatsby"],"plugins":[["prismjs",{"languages":["javascript","css","markup"],"plugins":["show-language"],"theme":"okaidia","css":true}]]}
Enter fullscreen modeExit fullscreen mode

With the installations and configurations out of the way, now we just need to importprismjs and use thePrism.highlightAll() function call to style our code blocks.

If you're using the repo I linked at the beginning, open thesrc/pages/index.js file and add the following:

importReactfrom"react"import{useEffect}from"react"importLayoutfrom"../components/layout"//import the Prism packageimportPrismfrom"prismjs"// The code we will be displayingconstcode=`const foo = 'foo';const bar = 'bar';console.log(foo + bar);`constIndexPage=()=>{useEffect(()=>{// call the highlightAll() function to style our code blocksPrism.highlightAll()})return(<Layout><divstyle={{display:"flex",alignItems:"center",flexFlow:"column nowrap",margin:"6px 10px",maxWidth:"800px",}}><h2>UsingPrismtostyle<code>codeblocks</code> in Gatsby</h2><divclassName="code-container"><pre><codeclassName="language-javascript">{code}</code></pre></div></div></Layout>)}exportdefaultIndexPage
Enter fullscreen modeExit fullscreen mode

Run thegatsby develop server and you will see the following page with the code block styled with the prism theme.

page using prism

Congratulations, now you know how to add code styles withPrism insideGatsby, here is a list of links to expand more on this topic.

Gatsby, React and PrismJs with remark

Parsing markdown files on gatsby is done with a transformer plugin calledgatsby-transformer-remark. This plugin takes markdown formatted content and transform it into valid html, so in this case, we are going to write our code snippets in triple backtick () inside markdown files (.md), useGraphQl to query the data inside the file and put it inside our code.

Let's start by creating a new blank gatsby project.

gatsby new gatsby-markdown-prism https://github.com/FidelVe/gatsby-blank-starter
Enter fullscreen modeExit fullscreen mode

Now, lets installprismjs,gatsby-transformer-remark andgatsby-remark-prismjs.

npminstall--save prismjs gatsby-transformer-remark gatsby-remark-prismjs
Enter fullscreen modeExit fullscreen mode

There are severalthemes to choose from inPrism, for this project I'm using theokaidia theme. In order to define a theme, create a file calledgatsby-browser.js in the root folder and add the following.

require("prismjs/themes/prism-okaidia.css");
Enter fullscreen modeExit fullscreen mode

Since we are going to be using.md files to write our code snippets in them, create a folder (src/content/). to put all the markdown files, and inside that folder create a new markdown file calledcode.md and add the following content.

markdown content

The next step is to configure the plugins we have installed. open thegatsby-config.js file at the root of the project and add the following:

module.exports={plugins:[{resolve:`gatsby-source-filesystem`,options:{name:`code`,path:`${__dirname}/src/content`,},},{resolve:`gatsby-transformer-remark`,options:{plugins:[{resolve:`gatsby-remark-prismjs`,options:{},},],},},],}
Enter fullscreen modeExit fullscreen mode

Thegatsby-source-filesystem plugin createsFile nodes from the files in our system. In this case, we are creating nodes from each file inside oursrc/content/ folder.

Every.md file we create inside oursrc/content/ folder gets parsed and transformed into valid html bygastby-transformer-remark, and because we are using thegatsby-remark-prismjs plugin, content inside triple backticks is automatically formatted byPrism.

Having installed and configured all the necessary plugins, the only thing that's left is inserting the parsed content into our page and for that we will useGraphQl.

Open thesrc/page/index.js file and add the following content to it.

importReactfrom"react"import{useStaticQuery,graphql}from"gatsby"importLayoutfrom"../components/layout"constIndexPage=()=>{constdata=useStaticQuery(graphql`    {      allMarkdownRemark(filter: { fileAbsolutePath: { regex: "/code.md/" } }) {        nodes {          html        }      }    }  `)return(<Layout><divstyle={{display:"flex",alignItems:"center",flexFlow:"column nowrap",margin:"6px 10px",maxWidth:"800px",}}><h2>UsingPrismtostyle<code>codeblocks</code> in Gatsby</h2><divclassName="code-container"dangerouslySetInnerHTML={{__html:data.allMarkdownRemark.nodes[0].html,}}></div></div></Layout>)}exportdefaultIndexPage
Enter fullscreen modeExit fullscreen mode

Start thegatsby develop server and you should see the code styled as shown in the image.

page with prism and markdown

Thanks for reading, hope this helped you implementPrism to yourGatsby pages.

Again, here is a list of links to expand more on this topic.

Top comments(8)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
alexhwoods profile image
Alex Woods
Software Engineer in ATL
  • Location
    Atlanta
  • Work
    Software Engineer at Ware2Go
  • Joined

The best resource I've read about this. I'm a very casual frontend engineer (I'm a backend engineer), so my Gatsby / React skills are "eh".

I had no idea the "remark" plugins were for dealing with markup files. This helped me solve my issue.

Thank you!

CollapseExpand
 
taphathoughts profile image
Tapha
Full Stack Developer / UX / Content
  • Location
    London, United Kingdom
  • Work
    Full Stack Developer
  • Joined

Hey Fidel, thanks for the great tutorial.

I'm wondering how you would do this with

dangerouslySetInnerHTML={{ __html: post.content.html }}

. When I followed your above steps, it did not work for me.

CollapseExpand
 
tweettamimi profile image
Tamimi
Just another developer chillin in an event-driven world of applications 🦄
  • Location
    Ottawa, Canada
  • Work
    Developer Advocate
  • Joined

Thanks for the article! I am wondering if you have ever incorporated a copy-to-clipboard functionality with the code block that is generated from thegatsby-remark-prismjs plugin. There seems to be a bunch ofprism specific plugins that are not accessible/exposed to thegatsby-remark-prismjs plugin. Thanks!

CollapseExpand
 
ncoughlin profile image
Nick Coughlin
  • Joined

I would love to see an addition to this that covers how to work with Prism Plugins within Gatsby, for exampleprismjs.com/plugins/show-language/

CollapseExpand
 
poutingemoji profile image
poutingemoji
  • Joined

As of 6/12/2021, there's still no way to use most Prism plugins like show-language with Gatsby. Someone made a pull request that added in the show-invisibles plugin though!github.com/gatsbyjs/gatsby/pull/21439

CollapseExpand
 
ashishkumar3 profile image
Ashish
  • Location
    india
  • Work
    student at not working
  • Joined

How to add file type on the code snippet?

CollapseExpand
 
apustula profile image
Aga
Discovering JavaScript along with React as a travel partner.
  • Location
    Warsaw
  • Work
    Frontend Developer
  • Joined

Thanks for your article, this is exactly what I was looking for!

CollapseExpand
 
tranduclinh197 profile image
Trần Đức Lĩnh
^^.> '10' + '1' = '11'.> '10' - '1' = '9'
  • Location
    Vietnam
  • Work
    KuLinhz at TechLiberal
  • Joined

Thanks.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

P-Rep for the ICON network / espanicon.team / fidel@espanicon.team
  • Location
    Venezuela
  • Education
    Chemical Engineer / Self-taught Programmer.
  • Work
    Web Developer (front-end, back-end, web3, etc)
  • Joined

More fromFidelVe

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp