gsundberg
gsundberg

Reputation: 547

Client-only Nuxt 3 Vue plugin

I am new to Nuxt and Vue, so go easy on me. I am trying to create a video player component in my Nuxt 3 app using vue3-video-player, which doesn't seem to support SSR based on the following error I get when I import it in my video component:

ReferenceError: navigator is not defined

This error persists even if the component is wrapped with <ClientOnly>. So, based on what I saw in the Nuxt 3 Documentation I thought I would create a client-only plugin located at plugins/vue3-video-player.client.js with the following contents:

import Vue3VideoPlayer from '@cloudgeek/vue3-video-player'

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

But when I try to use it in my component as <vue3-video-player>, I get the following error:

[Vue warn]: Failed to resolve component: vue3-video-player

So I guess my question is how do I create a client-only Vue component using Nuxt 3 plugins? Or is there an entirely different approach that would work better?

Upvotes: 15

Views: 31678

Answers (3)

JasonHorsleyTech
JasonHorsleyTech

Reputation: 545

To tag along with the given correct answer here,

If you're trying to install and use a third party NPM package, and running into "window is not defined" type errors, you can load the package as a plugin as follows (eg WAD)

npm install web-audio-daw

// plugins/wad.client.ts
import Wad from "web-audio-daw"
export default defineNuxtPlugin(nuxtApp => {
  return {
    provide: {
      Wad,
    }
  }
})
// pages/whatever.vue
<script lang="ts" setup>
const { $Wad } = useNuxtApp();
// Can use $Wad normally from here on out
</script>

Upvotes: 2

Dmitry Kaltovich
Dmitry Kaltovich

Reputation: 2270

Solution for nuxt 3:

Nuxt will automatically read the files in your plugins directory and load them. You can use .server or .client suffix in the file name to load a plugin only on the server or client side.

For example:

plugins/apexcharts.client.ts

Everything is so simple! And that is why we love nuxt ❤️


Solution for nuxt 2 (to show the difference):

nuxt.config.ts

  plugins: [
    {src: '~/plugins/apexcharts', mode: 'client'}
  ],

This is only for nuxt 2 because All plugins in your nuxt 3 plugins/ directory are auto-registered, so you should not add them to your nuxt.config separately.

Upvotes: 23

HexXx
HexXx

Reputation: 252

you could try to provide a helper function. As mentioned in the docs.

import Vue3VideoPlayer from '@cloudgeek/vue3-video-player'

export default defineNuxtPlugin((nuxtApp) => {
  
  return {
    provide: {
      Vue3VideoPlayer
    }
  }

})

Upvotes: 1

Related Questions