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 (3)

Collapse
 
luis_saraza_d818fb50bb68e profile image
Luis Saraza • Edited

Thanks!!, small comment here, if there is not support out of the box for a language, you might need to import the component for modern bundlers like this

import PrismJsx from 'prismjs/components/prism-jsx.min';

Or

import 'prismjs/components/prism-jsx.min';

Ref. github.com/PrismJS/prism/issues/11...

Collapse
 
arielmejiadev profile image
Ariel Mejia

Thanks, it is helpful!

Collapse
 
victorioberra profile image
Victorio Berra

Thanks! For TS you can do npm i --save-dev @types/prismjs