DEV Community

Ariel Mejia
Ariel Mejia

Posted on

Add Syntax Highlighter in NuxtJS 3 with Prism

First install Prism:

npm install prismjs;
Enter fullscreen mode Exit fullscreen mode

In any Vue component import Prism, default CSS and execute a highlightAll() method on mounted hook:

<script setup>
import { onMounted } from 'vue';
import Prism from "prismjs";
import "prismjs/themes/prism.min.css";

onMounted(() => {
  Prism.highlightAll();
});
</script>

<template>
<pre><code class="lang-js"><span>const x</span> = <span>'hello world'</span>;</code></pre>
</template>
Enter fullscreen mode Exit fullscreen mode

The code inside template tags is written manually using an online markdown to html converter, the original code is:

const x = 'hello world';
Enter fullscreen mode Exit fullscreen mode

Wrapped with three backticks and adding the language in this case "js", but this html could become from db or any API or CMS.

Customize Prism Theme

In this repo you can find multiple very well known code themes: prism-themes.

Just go to themes folder and copy the content of the desired theme (in my case dracula.css)

Create a file in assets/css/dracula.css

Instead of importing the default Prism styles, import in your Vue component custom theme CSS.

import "assets/css/dracula.css";
Enter fullscreen mode Exit fullscreen mode

Import CSS theme globally

In nuxt.config.ts add the theme directly to avoid import it multiple times:

export default defineNuxtConfig({
  devtools: { enabled: true },
  css: [
      '~/assets/css/main.css',
      '~/assets/css/dracula.css'
  ],
Enter fullscreen mode Exit fullscreen mode

As always thanks for reading and Happy Code!

Top comments (0)