- Key Concepts
- Directory Structure
- Going further
Plugins Directory
Nuxt automatically reads the files in yourplugins directory and loads them at the creation of the Vue application. You can use.server or.client suffix in the file name to load a plugin only on the server or client side.
All plugins in yourplugins/ directory are auto-registered, so you should not add them to yournuxt.config separately.
Which Files Are Registered
Only files at the top level of theplugins/ directory (or index files within any subdirectories) will be registered as plugins.
For example:
plugins|-myPlugin.ts//scanned|-myOtherPlugin|---supportingFile.ts//notscanned|---componentToRegister.vue//notscanned|---index.ts//currentlyscannedbutdeprecatedOnlymyPlugin.ts andmyOtherPlugin/index.ts would be registered. You can configureplugins to include unscanned files.
Creating Plugins
The only argument passed to a plugin isnuxtApp.
exportdefaultdefineNuxtPlugin(nuxtApp=>{// Doing something with nuxtApp})Object Syntax Plugins
It is also possible to define a plugin using an object syntax, for more advanced use cases. For example:
exportdefaultdefineNuxtPlugin({name:'my-plugin',enforce:'pre',// or 'post'asyncsetup (nuxtApp){// this is the equivalent of a normal functional plugin },hooks: {// You can directly register Nuxt app hooks here'app:created'() {constnuxtApp=useNuxtApp()// } }})If you are using an object-syntax plugin, the properties may be statically analyzed in future to produce a more optimized build. So you should not define them at runtime. For example, settingenforce: process.server ? 'pre' : 'post' would defeat any future optimization Nuxt is able to do for your plugins.
Plugin Registration Order
You can control the order in which plugins are registered by prefixing with 'alphabetical' numbering to the file names.
For example:
plugins/|-01.myPlugin.ts|-02.myOtherPlugin.tsIn this example,02.myOtherPlugin.ts will be able to access anything that was injected by01.myPlugin.ts.
This is useful in situations where you have a plugin that depends on another plugin.
In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example,10.myPlugin.ts would come before2.myOtherPlugin.ts. This is why the example prefixes single digit numbers with0.
Using Composables Within Plugins
You can usecomposables within Nuxt plugins:
exportdefaultdefineNuxtPlugin((NuxtApp)=>{constfoo=useFoo()})However, keep in mind there are some limitations and differences:
If a composable depends on another plugin registered later, it might not work.
Reason: Plugins are called in order sequentially and before everything else. You might use a composable that depends on another plugin which has not been called yet.
If a composable depends on the Vue.js lifecycle, it won't work.
Reason: Normally, Vue.js composables are bound to the current component instance while plugins are only bound tonuxtApp instance.
Automatically Providing Helpers
If you would like to provide a helper on theNuxtApp instance, return it from the plugin under aprovide key. For example:
exportdefaultdefineNuxtPlugin(()=>{return {provide: {hello: (msg:string)=>`Hello${msg}!` } }})In another file you can use this:
<template> <div> {{ $hello('world') }} </div></template><scriptsetuplang="ts">// alternatively, you can also use it hereconst {$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 ofuseNuxtApp() and within your templates.
If you need to use a provided helperwithin another plugin, you can calluseNuxtApp() 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:
declaremodule'#app' {interfaceNuxtApp {$hello (msg:string):string }}declaremodule'vue' {interfaceComponentCustomProperties {$hello (msg:string):string }}export { }If you are using WebStorm, you may need to augment@vue/runtime-core untilthis issue is resolved.
Vue Plugins
If you want to use Vue plugins, likevue-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! Seenuxt/nuxt#17143
First, install the plugin you want.
yarnadd--devvue-gtag-nextThen create a plugin fileplugins/vue-gtag.client.js.
importVueGtag, {trackRouter }from'vue-gtag-next'exportdefaultdefineNuxtPlugin((nuxtApp)=>{nuxtApp.vueApp.use(VueGtag, {property: {id:'GA_MEASUREMENT_ID' } })trackRouter(useRouter())})Vue Directives
Similarly, you can register a custom Vue directive in a plugin. For example, inplugins/directive.ts:
exportdefaultdefineNuxtPlugin((nuxtApp)=>{nuxtApp.vueApp.directive('focus', {mounted (el) {el.focus() },getSSRProps (binding,vnode) {// you can provide SSR-specific props herereturn {} } })})
