First install Prism:
npm install prismjs;
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>
The code inside template tags is written manually using an online markdown to html converter, the original code is:
const x = 'hello world';
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";
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'
],
As always thanks for reading and Happy Code!
Top comments (3)
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...
Thanks, it is helpful!
Thanks! For TS you can do
npm i --save-dev @types/prismjs