script setup and compiler macros

Intermediate · 14 min

What <script setup> compiles into, why defineProps, defineEmits, defineModel and the other define* macros need no import, and the rules that follow from that.

Before thisSingle-file componentsOptions API vs Composition API

Alexander Lichter · 14 min

script setup and compiler macros

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Alexander LichterReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `<script setup>` is compile-time sugar for a component's `setup()` function: the compiler wraps the block's code in `setup()` and exposes every top-level variable, function, and import to the template, so there's no `return { ... }` and no component registration.
  • `defineProps`, `defineEmits`, `defineModel`, `defineExpose`, `defineOptions`, `defineSlots`, and `withDefaults` are compiler macros, not functions: they need no import, only work inside `<script setup>`, and are replaced by component options during compilation.
  • Because props and emits declarations are hoisted out of `setup()` into the component's options, a runtime `defineProps({...})` argument can reference imports but not variables declared locally in the same block.
  • Since Vue 3.5, destructuring `defineProps()` stays reactive: the compiler rewrites each destructured name to `props.name`, and JavaScript default values work, but watching or passing one to a composable needs a getter such as `() => step`.
  • A `<script setup>` component is closed by default: a parent holding a template ref to it sees nothing unless the child lists what to share with `defineExpose`.
  • Top-level `await` in `<script setup>` makes the component's setup async, which means it must be rendered inside `<Suspense>`.

The boilerplate script setup removed

The Composition API’s original entry point is a setup() option. It runs once when a component instance is created, and whatever it returns becomes available to the template:

<script>
import { ref, computed } from "vue";
import PriceTag from "./PriceTag.vue";

export default {
  components: { PriceTag },
  props: { basePrice: Number },
  emits: ["purchase"],
  setup(props, { emit }) {
    const quantity = ref(1);
    const total = computed(() => props.basePrice * quantity.value);

    function buy() {
      emit("purchase", quantity.value);
    }

    return { quantity, total, buy };
  },
};
</script>

This works, but every name is written twice (declared, then returned), forgetting to return something gives a confusing “property not defined” warning, child components have to be registered, and props and emits are declared in a different place from where they’re used. Vue 3.2 introduced <script setup> to remove all of that:

<script setup>
import { ref, computed } from "vue";
import PriceTag from "./PriceTag.vue";

const props = defineProps({ basePrice: Number });
const emit = defineEmits(["purchase"]);

const quantity = ref(1);
const total = computed(() => props.basePrice * quantity.value);

function buy() {
  emit("purchase", quantity.value);
}
</script>

<template>
  <PriceTag :amount="total" />
  <input v-model.number="quantity" type="number" min="1" />
  <button @click="buy">Buy</button>
</template>

The rules are short. Everything at the top level of the block, including variables, functions, and imports, is available in the template. An imported component can be used as a tag directly. The code runs once per component instance, exactly like the body of setup(), because that’s what it compiles into.

What it compiles into

<script setup> is not a different runtime feature; it’s a compile-time transformation done by @vue/compiler-sfc (introduced in the single-file components lesson). The output is close to the setup() version above. Simplified, the compiler produces something like:

export default {
  props: { basePrice: Number },
  emits: ["purchase"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const quantity = ref(1);
    // ...
    return { quantity, total, buy, PriceTag }; // dev builds
  },
};

In production builds the compiler goes one step further and inlines the template’s render function into setup() itself, so the template reads local variables directly instead of going through a returned object. You can see both outputs in the Vue SFC Playground: its JS tab shows the compiled component, and the PROD switch in its header flips between development and production output.

Compiler macros: functions that aren’t

Look at defineProps and defineEmits again. They aren’t imported, yet they’re called like functions. That’s because they aren’t functions. They are compiler macros: markers the SFC compiler finds, removes, and replaces with component options, as in the compiled output above. They don’t exist at runtime. That explains every rule about them:

  • No import. There’s nothing to import. (Older code sometimes imports them from vue; current compilers just warn that the import is unnecessary.)
  • Only inside <script setup>. Anywhere else, nothing compiles them away.
  • Arguments can’t use local variables. Props and emits declarations are hoisted out of setup() into the module-level options object. Code inside the block becomes the body of setup(), so the hoisted declaration can’t see local variables. Imports and constants from a separate plain <script> block are fine.
import { MAX_QTY } from "@/config"; // fine, an import

const limit = 10; // declared in setup()

defineProps({
  qty: { type: Number, validator: (v) => v <= MAX_QTY }, // works
  // validator: (v) => v <= limit  ← compile error: can't reference `limit`
});

Here is the full set as of Vue 3.5:

Macro Since What it declares
defineProps() 3.2 The props this component accepts; returns the reactive props object.
defineEmits() 3.2 The events this component can emit; returns an emit function.
withDefaults() 3.2 Default values for type-based defineProps<...>() (largely replaced by destructure defaults in 3.5).
defineExpose() 3.2 What a parent can reach through a template ref.
defineOptions() 3.3 Other component options, such as name or inheritAttrs: false.
defineSlots() 3.3 Types for the component’s slots (TypeScript only).
defineModel() 3.4 A two-way bound prop for v-model; returns a ref.

You’ll use each in context later: props and emits in components and props and component events and emits, defineModel in v-model on components, inheritAttrs in fallthrough attributes, and defineExpose in template refs and defineExpose. With TypeScript, defineProps and defineEmits can take a type argument instead of a runtime object, defineProps<{ basePrice: number }>(), and the compiler generates the runtime declaration from the type; TypeScript with Vue covers that.

Not everything that looks like a macro is one. useSlots() and useAttrs() are real runtime functions and must be imported from vue.

Destructuring props in Vue 3.5

Before Vue 3.5, destructuring props broke reactivity: const { basePrice } = defineProps(...) copied the value once, and the variable never updated. Since 3.5, the compiler handles destructuring from defineProps specially. It rewrites every use of a destructured name into a property access on the props object, and you can use JavaScript default values:

<script setup>
const { basePrice, currency = "EUR" } = defineProps({
  basePrice: Number,
  currency: String,
});

// compiled roughly to: uses become props.basePrice and props.currency,
// and "EUR" moves into the props declaration as currency's default
const label = computed(() => `${basePrice} ${currency}`);
</script>

Inside computed, the template, or any function, this just works. The one trap is handing a destructured prop to something that needs to track it: watch(basePrice, ...) passes the current number, not a reactive source. Wrap it in a getter, watch(() => basePrice, ...), and do the same when passing it into a composable. Why that matters becomes clear in how Vue reactivity works.

Closed by default, and other consequences

Because a <script setup> component’s bindings live in a closure rather than on a returned object, a few behaviours differ from Options API components:

  • Closed to parents. A parent holding a template ref to the component sees none of its internals unless the child calls defineExpose({ ... }). This is deliberate: a component’s public surface is its props, events, slots, and whatever it explicitly exposes.
  • Top-level await is allowed. const product = await fetchProduct(id) at the top level makes the component’s setup async, and an async component has to be rendered inside <Suspense>. That pattern is covered in async components and Suspense.
  • A plain <script> can sit alongside. It runs once per module rather than once per instance, which suits module-level constants or named exports. Before defineOptions existed it was also how you set inheritAttrs or name.

What the video covers

Alexander Lichter starts from a Composition API component written with a plain setup() function, converts it to <script setup>, and asks why some calls need no import. He then goes through defineProps and defineEmits, the newer defineModel, and the remaining macros, plus a look at the community Vue Macros project that experiments with more. It’s the clearest short explanation of what a compiler macro is. Vue 3.5’s reactive props destructure gets less attention there, so the section above covers it. The two older videos in the links below are slower hands-on conversions; both predate defineModel, defineOptions, and props destructure.

Check yourself

  1. 01Why does `defineProps` work without being imported, while `ref` must be imported from `vue`?

    `ref` is a real runtime function exported by Vue. `defineProps` is a compiler macro: `@vue/compiler-sfc` recognizes the call while compiling `<script setup>`, turns its argument into the component's `props` option, and replaces the call with a reference to the props object. It doesn't exist at runtime, so there's nothing to import, and it would be an error outside `<script setup>`.

  2. 02Why does `const max = 10; defineProps({ count: { type: Number, validator: (v) => v <= max } })` fail to compile?

    The compiler hoists the props declaration out of `setup()` and into the component's options object at module level, but `max` is declared inside the `<script setup>` block, which becomes the body of `setup()`. The hoisted declaration can't see it. Moving `max` into an imported module, or a constant in a separate plain `<script>` block, fixes it.

  3. 03With Vue 3.5's reactive props destructure, why does `watch(step, ...)` not work while `watch(() => step, ...)` does?

    The compiler rewrites `step` to `props.step` wherever it appears, so `watch(step, ...)` passes the current value of `props.step`, a plain number, to `watch`, which can't track a number. Wrapping it in a getter means `watch` calls `() => props.step` and tracks that property access, so it re-runs when the prop changes.

  4. 04A parent uses a template ref to call `formRef.value.reset()` on a child written with `<script setup>`, and gets an error that `reset` is not a function. What's missing?

    `<script setup>` components are closed by default: their top-level bindings are available to their own template but not to a parent through a template ref. The child must call `defineExpose({ reset })` to make that function part of its public instance.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark