Syntax Highlighting with Prism.js and Next.js

Syntax Highlighting with Prism.js and Next.js

Prism.js is a compact, expandable syntax highlighter that was developed with modern web standards in mind.

To be able to use Prism.js with Next.js, the first thing you have to do is to add Prism.js to your project with

npm install prismjs

or

yarn add prismjs

Afterwards you need to import Prism.Js into all pages where you want code to be highlighted I am for example importing it into a layout component which wraps the whole web app:

js
Copy code
// in Layout.js
  import React,  { useEffect } from "react"
  const prism = require("prismjs")
  require('prismjs/components/prism-python');

  function Layout(props) {
    useEffect(() => {
      prism.highlightAll();
    }, []);
    
    // ...
  }

With this, all code tags are highlighted via a react hook. I also imported highlighting for Python because it's not included by default.

Now the only thing missing is the styling theme, which can simply be imported into _app.js with

js
Copy code
// in _app.js

  import "prismjs/themes/prism-tomorrow.css";
  
  export default function App({ Component, pageProps }) {
    return <Component {...pageProps} />;
  }

Instead of 'prism-tomorrow' you could also import the default-one or for example `prism-okaidia.

Have a look at https://prismjs.com/download.html to find all premade themes. Of course you can also create a custom theme.

First published September 22, 2020

    0 Webmentions

    Have you published a response to this? Send me a webmention by letting me know the URL.

    Found no Webmentions yet. Be the first!

    Write a comment

    About The Author

    Max
    Max

    Geospatial Developer

    Hi, I'm Max (he/him). I am a geospatial developer, author and cyclist from Rosenheim, Germany. Support me

    0 Virtual Thanks Sent.

    Continue Reading

    1. Dockerizing a Next.js Application with GitHub Actions

      In this article, we'll explore how to Dockerize a Next.js application and automate its deployment using GitHub Actions, thereby simplifying the deployment workflow and enhancing development productivity.

      Continue reading...

    2. Optimizing images for Next.js sites with imgproxy and docker

      How to transform and optimize images with imgproxy hosted with docker for your Next.js application.

      Continue reading...

    3. Building a Table of Contents (TOC) from markdown for your React blog

      How to create a Table of Contents (TOC) from markdown for your React blog with Javascript without any third party dependencies.

      Continue reading...