Unable to access global plugins in script tag when using Nuxt Vue with Typescript

Currently, I am in the process of converting a Nuxt Vue.js project (v2 not v3) into TypeScript, and I'm facing an issue where plugins are not recognized inside .vue files but work perfectly in .ts files.

In the code snippets below, you can see that even bootstrap vue and i18n are not recognized within .vue script tags, only functioning in .ts files. The workaround I found is to create a function that utilizes these plugins inside mixin.ts files and extend them accordingly. Alternatively, importing all plugins manually into each script also works. However, these methods defeat the purpose of global plugins. Am I missing something here? Why aren't they recognized by default?

I've also attempted to extend Vue directly in the main .vue components instead of using a mixin, but the same recognition issue persists.

Component.vue

<template>
  ...
  <div>
    {{$testFunction('test')}} Although this works, it lacks type indication or warnings 
  </div> 
</template

<script lang = "ts">
import Component, { mixins } from 'vue-class-component';
import { TableMixin } from '../../mixins/tablemixin';

@Component
class Contacts extends mixins(TableMixin) {
  test() {
    // Property '$testFunction' does not exist on type 'Contacts'.Vetur(2339)
    console.log(this.$testFunction('test'));
  }
  testMixin() {
    // Works fine through mixin...
    console.log(this.testMixinFunction('test'));
  }
}
export default Contacts;
</script>

mixins/tablemixin.ts

import Vue from 'vue';
import Component from 'vue-class-component';

@Component
export class TableMixin extends Vue { 
  testMixinFunction(str: string) {
    return this.$testFunction(str);
  }
}

plugins/helpers.ts

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $testFunction(str: string): string;
  }
}

Vue.prototype.$testFunction = (str: string): string => {
    return str + 'tested';
}

nuxt.config.js

plugins: [ 
  '~/plugins/helpers'
]

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "Node",
    "lib": [
      "ESNext",
      "ESNext.AsyncIterable",
      "DOM"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "experimentalDecorators": true,
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "nuxt-i18n",
      "bootstrap-vue"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

Answer №1

Seems like the issue stemmed from vetur itself, as the TS compiler had no problems with the global plugins. The problem arose because the project lacked the vetur.config.js file, causing it to search in the incorrect directory for the ts types (the project consists of client and api). By simply adding the vetur.config.js file and specifying the correct location, I was able to resolve the issue.

For those facing a similar problem, check out the solution detailed in the Vetur documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

Exploring the process of generating fresh component data using Vue.js's existing components

I have a Vue.js component that I am working with: Vue.component('channels-list', { data() { return { channels: [], } }, methods: { getChannels() { this.$http.get('/channels') ...

Within my component, I have incorporated two datepickers. My goal is to emit an object containing the values of both the start date and end date (referred to as startDateValue and

I have attempted to tackle this issue, but I am encountering the problem of receiving the same date value for both inputs. export class DateComponent implements OnInit { @Input() startDate: string; @Input() endDate: string; @Output() sendDate: Event ...

Creating TypeScript types using GraphQL code generation: Generating types without any other code

Utilizing the typescript plugin for graphql code generator As documented This TypeScript plugin is fundamental and capable of creating typings from GraphQLSchema, which can be leveraged by other typescript plugins. It creates types for all aspects of you ...

Angular: Issue encountered while attempting to differentiate an '[object Object]'. Arrays and iterables are the only permissible types for this operation

I encountered the following error message while attempting to retrieve updated data: Error trying to diff '[object Object]'. Only arrays and iterables are allowed Snippet of Get Code: allDatas allData(data) { this.allDatas = data } Up ...

Issue: "Stumbled upon an unknown provider! This often implies the presence of circular dependencies"

Looking for help on a perplexing error in my Angular / TypeScript app. While we wait for an improved error message, what steps can we take to address this issue? What are the potential triggers for this error to occur? Uncaught Error: Encountered undefi ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

What is the best way to access a variable from a .js file?

Is there a way to access a variable defined in a JavaScript file from a Vue file and pass it to the Vue file? In the following code snippet, there is a template.js file and a contact.vue file. The template file converts MJML to HTML and saves the output to ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

A guide on incorporating a set of components to be utilized as custom HTML elements in Angular

I am in the process of revamping my application to be more modular on the UI side, with a focus on separating different elements including: App header Left navigation panel Main content on the right side of the nav panel I have successfully figured out ...

evaluate a utility function that operates on children

In managing a component that requires children (referred to as the layout component), there is a specific function nested within this component that processes these child components. Testing this function poses a challenge, so I decided to extract it into ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

What is the process for implementing two-way data binding with v-html?

There is a div element in my code that has the attribute contenteditable="true". This div is intended to function similar to a textarea element. <div v-on:keyup.enter="SendMessage" v-html="message" contenteditable="true"></div> This is the co ...

"Customize your Vuetify v-card with uniquely styled rounded corners on only

I am seeking to create a unique v-card design where only two corners are rounded. Despite my attempts, the card ended up rotated by 90° and didn't achieve the desired outcome. DESIGN ATTEMPT: <div class="text-center rotate-ninety ml-n6" ...

How is it possible for Vue's controlled `<input />` to accept text input even without a handler specified?

Take a look at these minimal examples showcasing React and Vue Both include an <input />, with the value of the input bound to the state. React import React from "react"; export default function App() { const [value] = React.useState(&q ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

Potential explanation for unexpected Typescript initialization error

I am encountering the compiler error The property 'options' is not initialized or assigned in the constructor. However, upon reviewing the code for the respective class, it is clear that this reported error does not accurately reflect the actual ...

What is the best way to identify the browser back button using Vue.js?

I'm working on a component that requires specific logic to be executed when the user navigates back to my component using the browser's "back" button. Is there a specific property in Vue router or another method I can use to achieve this? What ...

The error message in TypeScript is indicating that the property 'x' is not found in the type '{}', which is required for a computed key

Description of a Typescript fragment: enum Field { age, bugs, } interface Foo { number_age: number; number_bugs: number; } function createFoo():Foo { let obj = {}; let index = 0; for (let key in Field) { obj['numb ...