
Code highlighting on blog posts are important since it adds aesthetics to the blog post as well as it visualizes the code provided.
Installing PrismJS
There are many ways to add PrismJS on Next.JS. But in this blog, I opted to use the yarn package manager. You may also use npm package manager or a CDN. To add PrismJS using yarn package manager, simply use the command: yarn add prismjs
Adding PrismJS CSS
In order to style the code part, the PrismJS CSS must be loaded in the application. In your _app.js, add the line
Your _app.js will look like this:
Adding PrismJS
In your blog post page, import the necessary files for PrismJs. In my case, the file is the [slug].js located on pages/posts/. The PrismJS files needed are the following:
Using PrismJS
Now, PrismJS can now be used to highlight code. For example we want to highlight the code:
First we need to encode the code using Coder's Toolbox. This is important so that characters like <, >, and " will be read as texts, and not a codes or html tags. The code will look like this after encoding:
Then, we need to contain that code inside <pre> and <code> tags. The code will now be:
Lastly, we will highlight the code. use this command:
Conclusion
There are some other methods like using babel, which is I personally use. But for starters, the way discussed in this blog post is more appropriate.