Skip to content

What Is a Compiler Macro in Vue?

In Vue, a compiler macro is a special function that can only be used inside <script setup> and is turned into plain JavaScript at build time. Macros arrived in Vue 3.2 together with the <script setup> syntax. They are not imported: the Vue compiler recognises them and converts them into component options, so they do not exist at runtime.

The most common compiler macros

  • defineProps: declares the props the component accepts.
  • defineEmits: declares the events the component emits.
  • defineExpose: chooses what a parent can reach through a template ref.
  • withDefaults: gives default values to props declared with TypeScript types.
  • defineModel (Vue 3.4+): declares a value bound two-way with v-model in a single line.
  • defineOptions and defineSlots (Vue 3.3+): declare component options and slot types.

Example

VueCode fragment
<script setup>
const props = defineProps({
  title: { type: String, required: true },
  count: { type: Number, default: 0 },
});
const emit = defineEmits(['increment']);
</script>

<template>
  <h2>{{ props.title }}</h2>
  <button @click="emit('increment')">Increment ({{ count }})</button>
</template>

Here defineProps and defineEmits are used without importing them. The compiler turns these calls into the component's props and emits options, which is why macros can only be called at the top level of <script setup> — not inside a function or in a regular <script> block.

The component (for example CounterTitle.vue) is used in another component like this:

VueCode fragment
<script setup>
import { ref } from 'vue';
import CounterTitle from './CounterTitle.vue';

const count = ref(0);
</script>

<template>
  <CounterTitle title="Counter" :count="count" @increment="count++" />
</template>

Note: For :key in v-for, the best choice is a unique and stable id for each item (for example item.id). Using the array index can lead to wrong matches when the list is sorted or items are added. This is a template rule, not a compiler macro.

Have a question about this article? Write to me