americanknight
americanknight

Reputation: 759

Typescripting custom plugins in Nuxt

In my Nuxt project, I created a custom plugin file that returns an object. /helpers/settings:

export const settings = {
  baseURL: 'https://my-site.com',
  ...
};

I register this file in /plugins/settings.ts:

import Vue from 'vue';
import { settings } from '~/helpers/settings';

Vue.prototype.$settings = settings;

And in nuxt.config.js:

export default {
  ...
  plugins: [
    '~/plugins/settings',

Then, in a component, I can use my plugin like so:

export default Vue.extend({
  data() {
    return {
      url: `${this.$settings.baseURL}/some-path`,

Everything works as expected, except in that in my console, I get a typescript error from the line that I refer to my plugin in my component:

Property '$settings' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, unknown, Readonly<Record<never, any>>>'.

Hence my question: what is the proper way to apply a type to my custom plugin so that I don't get this error every time I use it?

Upvotes: 2

Views: 6979

Answers (2)

HMilbradt
HMilbradt

Reputation: 4639

According to the docs, you'll need to augment the type file for Vue.

Place the following code in a file named plugin-types.d.ts.

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
  // 3. Declare augmentation for Vue
  interface Vue {
    $settings: string
  }
}

Upvotes: 5

David Benitez Riba
David Benitez Riba

Reputation: 918

This answer also work but I found an easier, though dirtier, way to fix it without the need of adding the plugin-types.d.ts file.

Just add a property to you componen with the name of plugin like following:

@Component
export default class YourComponent extends Vue {
  private $settings!: string; // your plugin here
  private url: string = `${this.$settings.baseURL}/some-path`
}

Upvotes: 0

Related Questions