How to do syntax highlighting in Next.JS

How to do syntax highlighting in Next.JS

|
1099

As a technical content writer, syntax highlighting (aka code beautifying) is a must-have thing for me. Code blocks are very often in my articles. And after moving to the next js, I had to figure out something to make the code blocks look cool, just like codes in an IDE like Visual Studio Code. So, I'll share how I figured out to show codes

from

function getFullName (user) {
    const fullName = user.firstName + user.lastName;
    return fullName;
}

to

function getFullName (user) {
    const fullName = user.firstName + user.lastName;
    return fullName;
}

Code Highlighting - Quick Solution

Here I'll quickly direct you how to do syntax highlighting using Prism JS without going into many details.

  1. Install prism js using npm / yarn

    npm i prismjs or yarn add prismjs

    It also provides TypeScript support, npm i @types/prismjs or yarn add @types/prismjs

  2. Import prismjs into your blog page and highlight all.

    The next step is just import prismjs into your codes and call the highlightAll function in your useEffect / componentDidMount.

    useEffect(() => {
        if (typeof window !== 'undefined') {
            Prism.highlightAll();
        }
    }, []);

    It will automatically select the code blocks and will highlight them all. Note, you must have your codes in the following format.

    <pre class="language-javascript" >
        <code>
            function getFullName (user) {
                const fullName = user.firstName + user.lastName;
                return fullName;
            }
        </code>
    </pre>

Highlight a specific language

Every programming language has different syntax, so prism js need to know, that from which language is your code belongs. It is written in the class of the pre tag. Below is an example

<pre class="language-java" >
    <code>
        class HelloWorld {
            public static void main(String[] args) {
                System.out.println("Hello, World!"); 
            }
        }
    </code>
</pre>

There only markup, css, clike and javascript languages are loaded by default by prism js to process. Any language besides from them, you need to load manually as shown below.

import "prismjs/components/prism-java";

Check out the whole list of supported languages.
https://prismjs.com/#supported-languages

Writing your own custom theme

Yes, you can write your own custom theme, which will override the default prism js theme. You can give styling to the class of each token, a global styles for all languages, language-wise styling and so on. You only need to learn the pattern of names of the classes for each kind.

Styling all languages

pre[class*="language-"],
code[class*="language-"] {

}

Language-specific styling

pre[class*="language-javascript"],
code[class*="language-javascript"] {
	color: #4ec9b0;
}

Token Specific stylings

.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
	color: #6a9955;
}

.token.punctuation {
	color: #d4d4d4;
}

.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
	color: #b5cea8;
}

Following if the full list of tokens language-wise
https://prismjs.com/faq.html#how-do-i-know-which-tokens-i-can-style-for

PrismJS functioning

Prism JS is a light-weight JavaScript library to tokenize your codes.

But what tokenization means?

Tokenization is dividing your code clock into categories, say in a code block, there are variables, constants, keywords, function names, and so on, and each of these categories called a token, so the whole processing is called tokenization.

Tokenization is done to give a colour to each token, like strings on your code block would be light brown, and variables would be blue-ish. The Color set for your code bock is called a theme, just like you change themes in VS Code or whatever IDE you use.

Bonus for readers

bonus of syntax highlitings
Photo by Joanna Kosinska on Unsplash

I have two bonus for all the readers. Maybe I can add some more bonuses for you with time 😉

Add buttons to code snippet to feels like a mac application

You must've noticed that my code snippets feel like of mac window. Isn't it cool? So I am exposing my source code only for you.

.blog-post pre{
    background-color: #eff0f1;
    padding: 16px;
    border-radius: 4px;
    overflow: auto;
    font-size: 14px;
    margin-bottom: 4.1rem;
    padding: 3.7rem 0 1.6rem .4rem;
    border-radius: 12px;
    overflow: hidden;
    background-image: url(your_url_to_image.png);
    background-repeat: no-repeat;
    background-size: 44px 10px;
    background-position: 16px 14px;
}

I am selecting all the pre tags that are under .blog-post class. You can download the png from below.

Macbook window action

The second bonus is the VS Code Default Dark theme (my favourite)

Below is the CDN link for the VS Code dark default theme. You can use it directly.
https://codepen.io/sirajalam049/pen/eYZyRBO.css

Or you can further customize it on codepen
https://codepen.io/sirajalam049/pen/eYZyRBO



Comments

© 2021 Garbage Valuegarbage value logo