How to properly add a global property to work in a component template? (Vue 3, vite, typescript, composition api)

756 Views Asked by At

The property does not work in the component

enter image description here

src/main.ts

import { createApp } from 'vue'
import languagePlugin from '@/plugins/languagePlugin'
import App from './App.vue'

const app = createApp(App)
app.use(languagePlugin)
app.mount('#app')

./src/plugins/languagePlugin.ts

import { App } from 'vue'

export default {
    install(app: App) {
        app.config.globalProperties.$t = (key: string): string => key
    }
}

package.json

{
  ...
  "type": "module",
  ...
  "dependencies": {
    ...
    "vue": "^3.2.47"
  },
  "devDependencies": {

    "@types/node": "^18.15.3",
    "@vitejs/plugin-vue": "^4.1.0",
    "@vue/eslint-config-typescript": "^11.0.2",
    "eslint": "^8.36.0",
    "eslint-plugin-vue": "^9.9.0",
    "typescript": "^4.9.5",
    "vite": "^4.2.0",
    "vue-tsc": "^1.2.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": false,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "types": [
      "vite/client"
    ],
    "lib": [
      "ESNext",
      "DOM"
    ],
    "skipLibCheck": true,
    "noEmit": true,
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue"
  ],
  "references": [
    {
      "path": "./tsconfig.node.json"
    }
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}

tsconfig.node.json

{
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "vite.config.ts"
  ]
}

./src/vite-env.d.ts

/// <reference types="vite/client" />

interface ImportMetaEnv {
    readonly VITE_APP_NAME: string
    readonly VITE_API_URL: string
}

interface ImportMeta {
    readonly env: ImportMetaEnv
}

./shims-vue.d.ts

declare module '*.vue' {
    import { defineComponent } from 'vue'
    const Component: ReturnType<typeof defineComponent>
    export default Component
}

./shims-vue-runtime-core.d.ts

export {}

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $t(key: string): string
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

This solution worked after I rebuilt the app

declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $t(key: string): string
    }
}
0
On

You need to reference the '$t' variable also in your main.ts. This is the only solution I've found. You can also try to define your property like so:

Object.defineProperty(app.config.globalProperties, '$t', {
        /* your definitions here */
      })