mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-14 10:04:05 +00:00
d365a45eb1
Co-authored-by: pooya parsa <pyapar@gmail.com>
74 lines
1.7 KiB
Markdown
74 lines
1.7 KiB
Markdown
---
|
|
icon: IconDirectory
|
|
title: 'plugins'
|
|
head.title: 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`](/docs/usage/nuxt-app).
|
|
|
|
```ts
|
|
import { defineNuxtPlugin } from '#app'
|
|
|
|
export default defineNuxtPlugin(nuxtApp => {
|
|
// Doing something with nuxtApp
|
|
})
|
|
```
|
|
|
|
## Typing plugins
|
|
|
|
If you provide a global property on the nuxt app instance, you can declare the type of this property like this:
|
|
|
|
```ts
|
|
import { defineNuxtPlugin } from '#app'
|
|
|
|
export default defineNuxtPlugin(nuxtApp => {
|
|
nuxtApp.provide('hello', msg => `Hello ${msg}!`);
|
|
})
|
|
|
|
declare module '#app' {
|
|
interface NuxtApp {
|
|
$hello (msg: string): string
|
|
}
|
|
}
|
|
```
|
|
|
|
## Vue plugins
|
|
|
|
If you want to use Vue plugins, like [vue-gtag](https://github.com/MatteoGabriele/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](https://github.com/nuxt/framework/discussions/1175)
|
|
|
|
First install the plugin you want.
|
|
|
|
```bash
|
|
yarn add --dev vue-gtag
|
|
```
|
|
|
|
Then create a plugin file `plugins/vue-gtag.client.js`.
|
|
|
|
```ts
|
|
import { defineNuxtPlugin } from "#app";
|
|
import VueGtag from "vue-gtag";
|
|
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
nuxtApp.vueApp.use(VueGtag, {
|
|
config: {
|
|
id: "GA_MEASUREMENT_ID",
|
|
params: {
|
|
anonymize_ip: true,
|
|
},
|
|
},
|
|
});
|
|
});
|
|
```
|