Search code examples
typescriptvue.jsvuejs3

How to add type support for global components in Vue 3?


So I have Component1,

<!-- Component1 -->
<script lang="ts" setup>
defineProps<{ msg: string }>()
</script>

<template>
  <p>{{ msg }}</p>
</template>

Then I register it globally,

// main.ts
import { createApp } from "vue"
import App from "./App.vue"
import Component1 from "./Component1.vue"

const app = createApp(App)
app.component("Component1", Component1)
app.mount("#app")

Afterwards I use it as,

<script setup lang="ts"></script>

<template>
  <Component1 />
</template>

However I don't get type inference for props for Component1. So how do I add typescript support for this global component?


Solution

  • The vue package exports a GlobalComponents interface that can be augmented with your global component's definition. For example, you could add the module augmentation in src/global-components.d.ts, as seen in the Volar docs:

    // src/global-components.d.ts
    import Component1 from '@/components/Component1.vue'
    
    declare module '@vue/runtime-core' {
      export interface GlobalComponents {
        Component1: typeof Component1,
      }
    }
    

    enter image description here