skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    An additional note

    If you use nuxt3 in SSR, your highlight.js plugin must contain the word client, like highlight.client.js and not highlight.js.

    Nuxt 3 relies on a SSR package that is not compatible with ESM modules.

    By using .client in the name of plugin, the module is imported only on the browser side and in ESM module.


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search