Nuxt/docs/content/3.docs/2.directory-structure/10.plugins.md
Daniel Roe 4e9a27257b
feat(nuxt3): automatically inject returns from plugins (#2001)
Co-authored-by: pooya parsa <pyapar@gmail.com>
2021-11-18 14:11:34 +01:00

2.5 KiB

icon title head.title
IconDirectory plugins Plugins directory

Plugins directory

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

::alert{type=warning} All plugins in your plugins/ directory are auto-registered, so you should not add them to your nuxt.config separately. ::

Creating plugins

The only argument passed to a plugin is nuxtApp.

import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin(nuxtApp => {
  // Doing something with nuxtApp
})

Automatically providing helpers

If you would like to provide a helper on the NuxtApp instance, just return it from the plugin under a provide key. For example:

import { defineNuxtPlugin } from '#app'

export default defineNuxtPlugin(() => {
  return {
    provide: {
      hello: () => 'world'
    }
  }
})

In another file you can use this:

<template>
  <div>
    {{ $hello() }}
  </div>
</template>

<script setup lang="ts">
// alternatively, you can also use it here
const { $hello } = useNuxtApp()
</script>

Typing plugins

If you return your helpers from the plugin, they will be typed automatically; you'll find them typed for the return of useNuxtApp() and within your templates.

::alert If you need to use a provided helper within another plugin, you can call useNuxtApp() to get the typed version. But in general this should be avoided unless you are certain of the plugins' order. ::

Advanced

For advanced use-cases, you can declare the type of injected properties like this:

declare module '#app' {
  interface NuxtApp {
    $hello (msg: string): string
  }
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $hello (msg: string): string
  }
}

export { }

Vue plugins

If you want to use Vue plugins, like vue-gtag to add Google analytics tags, you can use a nuxt plugin to do so.

There is an Open RFC to make this even easier! See nuxt/framework#1175

First install the plugin you want.

yarn add --dev vue-gtag-next

Then create a plugin file plugins/vue-gtag.client.js.

import { defineNuxtPlugin } from '#app'
import VueGtag from 'vue-gtag-next'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(VueGtag, {
    property: {
      id: 'GA_MEASUREMENT_ID'
    }
  })
})