Bildquelle: ESA/DLR/FU Berlin; CC BY-SA 3.0 IGO (modified)

Syntax Highlighting with Prism and Next.js

By Max Dietrich | Geospatial specialist, Web-Developer.

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

To be able to use Prism with Next.js, the first thing to do is to install prism: You can either use the npm package with

npm install prismjs or yarn add prismjs

or download a corresponding CSS and JS file from https://prismjs.com/download.html.

It is best to import Prism directly into a separate layout component with:

 // 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. Also i imported highlighting for Python because it's not included by default.

Now the only thing missing is the appropriate code visualisation, which can simply be imported into _app.js

 // in _app.js
  import "../styles/global.scss";
  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 or for example `prism-okaidia'.

More Articles:

Hosting NextJS on a private server using PM2 and Github webhooks as CI/CD

This article shows you how can host your Next.js site on a server with a CI/CD pipeline via PM2 and Github Webhooks.

How to create a Mailchimp newsletter sign-up-form for your Gatsby Site

Managing your own newsletter is crucial for creating a sustainable online-business. With E-Mails you can build a relationsship with your audience and engage with them so they will drive some nice traffic to your new post or whatever you just have published and want to promote.

GatsbyJS with CI/CD Pipeline via Codebuild

With the free tier for AWS you always get one active AWS code pipeline per month and 100 minutes of AWS code build per month with which you can create a CI / CD pipeline for a GatsbyJS site.

I am Max Dietrich.

I am currently working as Geodata-Manager at RIWA.
I love to experiment with web-applications which i am documenting on this site.

Recent Articles

    Good Links

    • All Articles
    • Site Stats
    • About this site
    • Disclaimer & Imprint

    Connect

    You can connect with me on:
    Copyright © 2020 Max Dietrich. All Rights Reserved.
    Made with ❤️ by MXD.