Skip to content

What Is a Macro in Vue?

In the Vue world, "macro" usually means one of two things: Vue's own compiler macros and the community project Vue Macros. What they have in common is that they are turned into regular code at build time and add no runtime cost.

1. Compiler macros

Compiler macros are functions used inside <script setup> without being imported: defineProps, defineEmits, defineExpose, withDefaults, defineModel, defineOptions and defineSlots. See What Is a Compiler Macro in Vue? for details and examples.

VueCode fragment
<script setup>
const props = defineProps({ name: String });

// A parent can call greet() through a template ref
defineExpose({ greet: () => `Hello ${props.name}` });
</script>

<template>
  <p>Hello, {{ name }}!</p>
</template>

2. The Vue Macros project

Vue Macros is a community project that provides, experimentally, macros Vue does not offer officially yet. It is added to a project as a Vite or webpack plugin. Some ideas tried there were later adopted by Vue itself; defineOptions is one example.

Why macros?

  • Less boilerplate code.
  • Better TypeScript type inference.
  • Shorter, more readable component definitions.

In return, macros need a build step and only work at the top level of <script setup>.

Have a question about this article? Write to me