Nuxt Plugins Typescript

Create a plugin

Create a file in plugins folder with .ts extension.
For example, puppy.ts

class Puppy {
  constructor() {}

  bark() {
    console.log('Puppy::bark')
  }
}

Register the plugin

Add the plugin to nuxt.config.ts file.

plugins: ['~/plugins/puppy.ts'],

Injecting plugin

Let's inject our plugin into Nuxt Context
by adding a new property to the context under @nuxt/types.

Add folloging code to plugins/puppy.ts file.

import Vue from 'vue'
import { Plugin } from '@nuxt/types'

class Puppy {
  ...
}

declare module '@nuxt/types' {
  interface Context {
    $puppy: Puppy
  }
}

const puppyPlugin: Plugin = (context) => {
  context.$puppy = new Puppy()
}

export default puppyPlugin

Usage

<template>
    ...
</template>

<script lang="ts">
import { defineComponent, useContext } from '@nuxtjs/composition-api'

export default defineComponent({
  setup() {
    
    const { $puppy } = useContext()
    $puppy.bark()
    
    return {}
  },
})
</script>

References:

Helpful?

If you think this is helpful 🎈
Don't keep it to yourself 🙊

Share it with your lovely followers at twitter 🗽

lets connect viatwitter