Writing

Hard-Won Lessons from Building with Vue 3, TypeScript, and script setup

Migrating from Vue 2 Options API to modern Vue 3 with TypeScript represents a fundamental shift in component authoring.

Here are the pragmatic architectural lessons and testing pitfalls encountered while building a production-grade Vue 3 TypeScript application.

1. Embrace <script setup> Fully

Early Vue 3 codebases relied on explicit setup(props, context) functions that returned dictionaries of variables. Today, <script setup> is the official standard.

<script setup lang="ts">
import { ref, computed } from 'vue';

// Typed props with compile-time defaults
const props = withDefaults(
  defineProps<{
    title: string;
    threshold?: number;
  }>(),
  { threshold: 10 }
);

// Typed emits
const emit = defineEmits<{
  (e: 'update', value: number): void;
  (e: 'close'): void;
}>();

const count = ref(0);
const isExceeded = computed(() => count.value > props.threshold);
</script>

Why it wins:

  • Zero boilerplate: No returning objects from functions; top-level variables and imports are directly available to <template>.
  • First-class TypeScript: defineProps<T>() and defineEmits<T>() provide pure compile-time type definitions.
  • Superior runtime performance: Templates compile into render functions in the same scope, avoiding proxy overhead.

2. Asynchronous Components & Top-Level await with <Suspense>

When a component uses top-level await inside <script setup>, it automatically becomes an asynchronous component.

To render it safely, the parent tree must wrap it in <Suspense> with a fallback loading slot:

<template>
  <router-view v-slot="{ Component }">
    <Suspense :timeout="0">
      <component :is="Component" />
      <template #fallback>
        <div class="skeleton-loader">Loading content...</div>
      </template>
    </Suspense>
  </router-view>
</template>

Setting :timeout="0" guarantees the fallback UI renders immediately upon route transitions instead of delaying until a debounce threshold.

3. Unit Testing Asynchronous <script setup> Components

Testing <script setup> components with @vue/test-utils requires adjusting testing habits:

  1. Test the public template interface: Because <script setup> scopes bindings locally (closed by default), avoid attempting to inspect internal variables via wrapper.vm.internalVar. Test behavior via DOM interactions, rendered text, and emitted events.
  2. Mounting async components: Flush microtask promises to ensure top-level await resolves before making assertions:
import { mount, flushPromises } from '@vue/test-utils';
import { defineComponent, h, Suspense } from 'vue';
import UserProfile from '@/components/UserProfile.vue';

// Wrap async component in Suspense for testing
const AsyncWrapper = (component: any) =>
  defineComponent({
    render() {
      return h(Suspense, null, {
        default: () => h(component),
        fallback: () => h('div', 'Loading...'),
      });
    },
  });

test('renders user profile after async fetch', async () => {
  const wrapper = mount(AsyncWrapper(UserProfile));
  await flushPromises();

  expect(wrapper.find('h1').text()).toBe('Jane Doe');
});

4. Skip Vuex; Adopt Pinia and VueUse

  • Pinia over Vuex: Pinia is the official Vue state management library. It discards verbose mutations, supports complete TypeScript type inference automatically without custom wrappers, and allows defining stores using standard setup syntax (defineStore('id', () => { ... })).
  • Leverage VueUse: Avoid reinventing common lifecycle utilities. @vueuse/core provides battle-tested composables for debouncing, viewport intersection, local storage synchronization, and window listeners that automatically clean up on unmount.

Summary

The combination of <script setup>, TypeScript generics, Pinia, and VueUse offers one of the most productive, enjoyable developer experiences in modern frontend engineering.