Exploring Vue 3: Crafting a custom plugin using the composition API and enhancing it with Typescript type augmentation

Encountering an issue with displaying plugins properly within <script> and <template> tags on WebStorm.

Firstly, let's take a look at my files and configuration:

tsconfig.config.json

{
  "extends": "@vue/tsconfig/tsconfig.node.json",
  "include": ["vite.config.*", "vitest.config.*", "cypress.config.*", "playwright.config.*", "src/i18n.d.ts"],
  "compilerOptions": {
    "composite": true,
    "types": ["node"]
  }
}

package.json

{
  "name": "my-app",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "vite",
    ...
  },
  "dependencies": {
    "pinia": "^2.0.28",
    "vue": "^3.2.45",
    ...
  },
  "devDependencies": {
    "@rushstack/eslint-patch": "^1.1.4",
    ...
  }
}

Project structure https://i.sstatic.net/il2IV.png

Made a custom i18n plugin for testing purposes in a clear Vue project setup.

...

In template I receive a warning, but it works during runtime. However, including the plugin in the script section causes an error.

I'm puzzled by this situation. Any assistance would be greatly appreciated :)

Answer №1

To ensure proper functionality, it is imperative to include $translation in the script section of your code. Global variables cannot simply materialize out of thin air; unless some form of magical transformation like Unplugin is applied. To achieve this, it must be exported as shown below:

export let $translation: (key: string) => string;

export const plugin = {
    install(app: App, options: any) {
        $translation = (key: string) =>  {...};
        app.config.globalProperties.$translation = $translation
    }
}

In Vue 3, consider using type augmentation with @vue/runtime-core instead of just vue:

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $translation: (key: string) => string;
    }
}

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

What is the most efficient way to update data multiple times by mapping over an array of keys in a react hook?

My question might not be articulated correctly. I'm facing an issue with dynamically translating my webpage using Microsoft's Cognitive Services Translator. I created a react hook for the translator, which works well when I need to translate a si ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

The issue of inconvenience arises when dealing with `as const` arrays, as the readonly T[] is not directly assignable to T[]. The challenge lies in how to effectively remove

I encounter this issue repeatedly (playground link): const arr = [1,2,3] as const const doSomethingWithNumbers = <T extends number[]>(numbers: T) => {} doSomethingWithNumbers(arr) // ^ // Argument of type 'readonly [1, 2 ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

Error in TypeScript - Anticipated 1-2 arguments, received either none or multiple. Code Issue TS2556

While working in JavaScript, I had no issues with this code snippet. However, when I attempted to implement it in a TypeScript Project, an error surfaced. The problem seems to revolve around the fetch(...args) function call. const fetcher = (...args) =&g ...

The trim() method in Vue.JS does not properly handle trimming a passed string

I've been attempting to eliminate white space from a property of one of the returned objects using the .trim() function, but it's not working as expected. Even after trying JavaScript functions like .replace(/\s/g,''), the issue p ...

Linking a string value to a specific data structure in TypeScript

I'm currently exploring typescript and I have a question about mapping a string value to a custom type when using templates in function calls. For instance: object.method<TypeMapper['CustomType']>([...]) In this scenario, 'Cust ...

Encountering Thumbnail Type Error While Implementing Swiper in Next.js

When trying to integrate Swiper with Next.js, I ran into an issue concerning thumbnails. "onSwiper={setThumbsSwiper}" This line is causing a TypeScript error: swiper-react.d.ts(23, 3): The expected type comes from property 'onSwiper' w ...

The function did not return a Promise or value as expected when using async and await

    I have been working on implementing this code structure for my cloud functions using httpRequest. It has worked seamlessly with those httpRequest functions in the past. However, I recently encountered an error when trying to use it with the OnWrite ...

Retrieve a collection of Firebase records using a specific query parameter

I'm currently developing a web app with Angular 2 and facing an issue with retrieving data from Firebase based on specific conditions in the child node. Here's how my Firebase structure looks like: I need to extract the entry for the one with app ...

actions with frontend routing for CRUD operations

Imagine you are creating a simple CRUD todo application. Whether you choose to use Angular, React, or Vue for routing, the setup will be similar: /todos => see all todos /todos/:id => view one todo by id /todos/:id/edit => edit one todo by id /t ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

Is there a way to retrieve the name of a document stored within a collection using Firebase Firestore and Firebase Storage

When fetching data from the 'users' collection in Firebase Firestore and mapping the response, I have a function that converts the array of domains and filters out any domains that do not meet certain criteria. Here's an example: Sample dom ...

Avoid clicking on the HTML element based on the variable's current value

Within my component, I have a clickable div that triggers a function called todo when the div is clicked: <div @click="todo()"></div> In addition, there is a global variable in this component named price. I am looking to make the af ...

Employing Bazel in conjunction with Lerna and Yarn workspaces

It seems that a lot of people are currently utilizing lerna and/or yarn workspace. I'm thinking about either transitioning from them to Bazel, or perhaps integrating them with Bazel in conjunction with an example project for guidance. Take for insta ...

How can Vue-toastr and Vue2 be configured with global options for toastr notifications?

I'm currently utilizing vue-toastr in my project, which combines Laravel 5.5 and Vuejs 2. Although the toasts are displaying correctly, I am struggling to set global options for them, such as position... I have attempted to do this but have been uns ...

Retrieving the row value of a checkbox in an Angular table

I'm facing a challenge where I have a table with three columns, one of which is a checkbox. Here is an image for reference: https://i.sstatic.net/4U6vP.png Here is the code snippet: <div nz-row> <nz-table nz-col nzSpan="22" [nzLoading] ...

Does not have any exported elements

Recently, I've started learning Typescript and experimenting with express js. However, I’ve encountered a problem where the server displays an error message stating that '...../routes.ts' has no exported member 'router'. Despite ...

Encountering a TypeError while working with Next.js 14 and MongoDB: The error "res.status is not a function"

Currently working on a Next.js project that involves MongoDB integration. I am using the app router to test API calls with the code below, and surprisingly, I am receiving a response from the database. import { NextApiRequest, NextApiResponse, NextApiHandl ...