javascriptvuejs3nuxt3.jshighlight.js

How to create highlightjs plugin on nuxt3


I try to create a plugin in nuxt3 that uses highligh.js and use it on my components. But I can't do it

I make this :

// @/plugins/highlight.js

import 'highlight.js/styles/stackoverflow-light.css'
import hljs from 'highlight.js/lib/core';
import json from 'highlight.js/lib/languages/json';

hljs.registerLanguage('json', json);

import 'highlight.js/styles/vs.css'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(hljs)
})

I want to use like this :

// @/components/JSONView.vue
<template>
  <highlightjs
    language="json"
    :code="myCode"
   />
</template>

<script setup>

const code = ref('{ "done": true }')

</script>

Thanks in advance


Solution

  • You can use the official Vue plugin from highlight Js

    npm i @highlightjs/vue-plugin

    ~/plugins/highlight.client.ts

    import hljs from 'highlight.js/lib/core'
    import javascript from 'highlight.js/lib/languages/javascript'
    import highlightJS from '@highlightjs/vue-plugin'
    import 'highlight.js/styles/atom-one-dark.css'
    
    export default defineNuxtPlugin((nuxtApp) => {
        hljs.registerLanguage('javascript', javascript)
        nuxtApp.vueApp.use(highlightJS)
    })

    Component usage

    <script setup lang="ts">
    const JSONEXample = JSON.stringify({ firstName: 'John', lastName: 'Wick', age: 37 }, null, 3)
    </script>
    <template>
      <main>
        <ClientOnly>
          <highlightjs
              autodetect
              :code="JSONEXample"
          />
        </ClientOnly>
      </main>
    </template>

    Tested and it works. enter image description here