Woman (Marguerite) taking a selfie in the mirror, phone in hand, wearing a RHCP shirt.

Marguerite Roth

Senior Product Engineer @Parse.ly

The Prism.js library has never been the most comfortable spot for me.

Here is where I landed — PrismJS component for formatting code in a Vue / SSG environment, supported in markdown.

THIS. How do I make this stylized code snippet? ^ Code in code is too much.

So let’s look at how to build a Prism component for use in an SSG environment. PrismJS is the go-to syntax highlighter library for making it easy to add code formatting to a website. This component formats all snippets in these blog posts (JavaScript, Python, Markdown, Bash, etc).

What is Prism.js?

Prism is a syntax highlighter library that supports a wide range of languages. It allows you to add code formatting to your website, making it easier for users to read and understand code snippets. The Prism library can be configured to highlight specific languages or customize the look and feel of the formatted code.

Building a Prism component for Vue/Vite/SSG

I knew I wanted to have some sort of code formatting happening on these posts in my website and I knew I’d have to use Prism. However, because I’m running a custom Vue/Vite setup, I had to do some knitting to have this formatting run on the client side.

This code creates a <CodeSnippet/> component that can be used to format code snippets in any Vue or Markdown component. It uses the highlight method to apply Prism syntax highlighting to the code and the copyCode method to enable users to copy the formatted code to their clipboard.

Where the magic happens

I initially imported and called Prism like any other imported module, alongside the other imports:

But no — we need to call this minified .js file in an async/await since we’re building static pages:

In this component, we’ll creat a prop to denote languagethis.language:

When using the component, we can set the language by passing in language:

In conclusion, Prism.js is a powerful highlighter library that makes it easier to add code formatting to a website. By building a Prism component for Vue/Vite/SSG, we can format all snippets with JavaScript, Python, Markdown, Bash, and more.