Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging Face Frontier Reasoning Traces

Develop a Vue 3 application with Composition API and TypeScript for a large-scale project.

  1. User

    Develop a Vue 3 application with Composition API and TypeScript for a large-scale project.

  2. Gemini Assistant

    Refining Architecture Plans

    I'm currently focused on the implications of "large-scale." I'm diving deep into component design patterns and state management strategies. Considering modularity and scalability are paramount. I'm prioritizing clear separation of concerns, ensuring maintainability as the project grows. I'm exploring different methods to structure the project directory to reflect these goals.

    Clarifying Scale Differentiation

    I'm now zeroing in on defining the key differences between small and large applications. It's becoming evident that organization is crucial, so I'm thinking about structuring files functionally or by domain. I'm prioritizing typed state management with Pinia, implementing lazy-loaded routes with guards and types, and creating an abstraction layer for API calls with interfaces. I also want to make sure I have reusability baked in, with hooks and atomic components. Code splitting is a must for performance, as is rigorous testing, and linting/formatting rules for team consistency.

    Organizing the Application

    I'm solidifying my approach to project structure, emphasizing modularity for scalability. The current focus is on a hybrid "screaming architecture," including assets, components, composables, layouts, modules, router, services, stores, and types. This approach seems ideal for large-scale development, using modules to encapsulate specific domains. The separation of concerns is being carefully considered, and I'm also thinking about using Axios (or a Fetch wrapper) for API calls. I also have to think about testing, and UI libraries such as Tailwind or a UI kit. I'll probably stick to CSS/SCSS to keep the focus on architecture.

    Crafting Code Samples

    I'm now starting on the code examples, beginning with npm create vue@latest for the setup. I'm focusing on an API layer, needing a singleton Axios instance with interceptors and a generic request function for proper type handling. For state management, I'm setting up a User/Auth store using the setup store syntax in Pinia, which works well with Composition API. I'll also add composables like useAsync to show shared logic. I'm also implementing a "Products" module/feature structure at src/modules/products/ including routes, store, and views. Finally, I'll be implementing components with <script setup lang="ts">, including defineProps with interfaces and async/await with Suspense or onMounted.

    Building the Tutorial Steps

    I'm currently building the steps for the guide. First, I'll scaffold the project, and then I'll explain the project directory structure and why it's set up this way. Afterwards, I'll explain important configuration, networking using an Axios wrapper, and state management via an Auth store. The core will be feature development, including the Product module and modular routing. I'll cap it off with global components. Finally, I'll review and refine my work by considering scalability and other important points.

    Resolving Module Routing

    I'm presently working on refining the routing within the product module, thinking about where to define the routes. I've decided to keep route definitions inside the modules for organization. I need to remember to import these routes for everything to work correctly. I'm also ensuring that I define return types explicitly in my API calls and avoiding the use of any types. I'm also implementing a best practices list with quick tips for testing, CI/CD, and linting. I need to explain the defineModel or defineProps generic syntax as well. I'm getting close to generating the final markdown output.

    For a large-scale Vue 3 application, organization and abstraction are key. You want to avoid a massive flat structure and instead embrace a Modular/Domain-Driven Design.

    Here is a comprehensive guide and architectural blueprint for building a scalable application using Vue 3, Composition API (<script setup>), TypeScript, Pinia (State), and Vite.


    1. Project Structure (The "Modular" Approach)

    Instead of grouping by file type (putting all views in views/, all stores in stores/), group by feature. This allows teams to work on specific domains (e.g., "Auth", "Dashboard", "Products") without stepping on each other.

    src/
    ├── app/                    # Global Application Setup
    │   ├── router.ts           # Main Router entry
    │   ├── main.ts             # Entry point
    │   └── App.vue             # Root component
    ├── common/                 # Shared logic & UI across the app
    │   ├── components/         # Atomic UI (Buttons, Inputs)
    │   ├── composables/        # Shared hooks (useTheme, useWindowResize)
    │   ├── utils/              # Date formatting, validation regex
    │   └── types/              # Global TypeScript interfaces
    ├── config/                 # Env vars, constants
    ├── layouts/                # App shells (DefaultLayout, AuthLayout)
    ├── modules/                # DOMAIN SPECIFIC LOGIC (The core)
    │   ├── auth/
    │   │   ├── components/     # Components specific to Auth
    │   │   ├── store/          # Pinia store for Auth
    │   │   ├── views/          # Pages (Login, Register)
    │   │   └── routes.ts       # Routes specific to Auth
    │   └── products/
    │       ├── components/
    │       ├── store/
    │       ├── types/          # Module-specific types
    │       ├── views/
    │       └── routes.ts
    └── services/               # API layers, 3rd-party libs (Axios, WebSocket)
    

    2. Configuration & Environment

    tsconfig.json

    Ensure strict typing.

    {
      "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "strict": true,
        "jsx": "preserve",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "types": ["vite/client", "node"],
        "paths": {
          "@/*": ["./src/*"]
        }
      }
    }
    

    3. The Network Layer (Axios + TypeScript)

    Don't call axios.get directly in components. Create a service wrapper to handle types, interceptors, and error handling globally.

    src/services/api.ts

    import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
    
    const apiClient: AxiosInstance = axios.create({
      baseURL: import.meta.env.VITE_API_URL || '/api',
      headers: {
        'Content-Type': 'application/json',
      },
      timeout: 10000,
    });
    
    // Interceptors for Auth Token
    apiClient.interceptors.request.use((config) => {
      const token = localStorage.getItem('token');
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });
    
    // Generic API Function
    export const api = {
      get: <T>(url: string, config?: AxiosRequestConfig) => 
        apiClient.get<T>(url, config).then((res) => res.data),
    
      post: <T>(url: string, data: unknown, config?: AxiosRequestConfig) => 
        apiClient.post<T>(url, data, config).then((res) => res.data),
        
      // ... put/delete
    };
    

    4. State Management (Pinia with Composition API)

    For large apps, use Setup Stores (syntax similar to standard Composition API). It is much more flexible than Option Stores.

    src/modules/products/store/productStore.ts

    import { defineStore } from 'pinia';
    import { ref, computed } from 'vue';
    import { api } from '@/services/api';
    import type { Product } from '../types';
    
    export const useProductStore = defineStore('products', () => {
      // State
      const products = ref<Product[]>([]);
      const loading = ref<boolean>(false);
      const error = ref<string | null>(null);
    
      // Getters (Computed)
      const totalProducts = computed(() => products.value.length);
      const availableProducts = computed(() => products.value.filter(p => p.inStock));
    
      // Actions
      async function fetchProducts() {
        loading.value = true;
        error.value = null;
        try {
          // The generic <Product[]> ensures type safety for the response
          const data = await api.get<Product[]>('/products');
          products.value = data;
        } catch (err: any) {
          error.value = err.message || 'Failed to load products';
        } finally {
          loading.value = false;
        }
      }
    
      return { products, loading, error, totalProducts, availableProducts, fetchProducts };
    });
    

    5. Domain Module Implementation

    Here is how a Feature Module (e.g., Products) looks. Notice how we separate the type definitions and the view.

    src/modules/products/types/index.ts

    export interface Product {
      id: number;
      name: string;
      price: number;
      inStock: boolean;
    }
    

    src/modules/products/views/ProductList.vue Using <script setup lang="ts">

    <script setup lang="ts">
    import { onMounted } from 'vue';
    import { storeToRefs } from 'pinia';
    import { useProductStore } from '../store/productStore';
    import ProductCard from '../components/ProductCard.vue';
    
    // Initialize Store
    const store = useProductStore();
    
    // Destructure state (use storeToRefs to keep reactivity)
    const { products, loading, error } = storeToRefs(store);
    // Destructure actions (can be destructured directly)
    const { fetchProducts } = store;
    
    onMounted(() => {
      fetchProducts();
    });
    </script>
    
    <template>
      <div class="product-page">
        <h1>Catalog</h1>
    
        <div v-if="loading">Loading items...</div>
        
        <div v-else-if="error" class="error">
          {{ error }}
        </div>
    
        <div v-else class="grid">
          <!-- Props are type-checked automatically -->
          <ProductCard 
            v-for="product in products" 
            :key="product.id" 
            :product="product" 
          />
        </div>
      </div>
    </template>
    
    <style scoped>
    .grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
    .error { color: red; }
    </style>
    

    src/modules/products/components/ProductCard.vue Typed Props

    <script setup lang="ts">
    import type { Product } from '../types';
    
    // Define props with interface
    interface Props {
      product: Product;
    }
    
    // Defaults can be added with withDefaults generic (optional)
    defineProps<Props>();
    
    const emit = defineEmits<{
      (e: 'addToCart', id: number): void
    }>();
    </script>
    
    <template>
      <div class="card">
        <h3>{{ product.name }}</h3>
        <p>{{ product.price }} USD</p>
        <button @click="emit('addToCart', product.id)">Add +</button>
      </div>
    </template>
    

    6. Scalable Routing

    Do not write all routes in one file. Each module should define its own routes, which are aggregated in the main router.

    src/modules/products/routes.ts

    import type { RouteRecordRaw } from 'vue-router';
    
    const routes: RouteRecordRaw[] = [
      {
        path: '/products',
        name: 'Products',
        component: () => import('./views/ProductList.vue'), // Lazy loading
        meta: { requiresAuth: true }
      },
      {
        path: '/products/:id',
        name: 'ProductDetail',
        component: () => import('./views/ProductDetail.vue'),
      }
    ];
    
    export default routes;
    

    src/app/router.ts

    import { createRouter, createWebHistory } from 'vue-router';
    import productRoutes from '@/modules/products/routes';
    import authRoutes from '@/modules/auth/routes';
    
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        { path: '/', redirect: '/products' },
        ...authRoutes,
        ...productRoutes,
        
        // Catch-all 404
        { path: '/:pathMatch(.*)*', component: () => import('@/common/views/NotFound.vue') }
      ]
    });
    
    export default router;
    

    7. Reusable Composables

    Logic that isn't tied to one specific module goes into src/common/composables.

    src/common/composables/useScreen.ts

    import { ref, onMounted, onUnmounted } from 'vue';
    
    export function useScreen() {
      const width = ref(window.innerWidth);
      const isMobile = ref(width.value < 768);
    
      const update = () => {
        width.value = window.innerWidth;
        isMobile.value = width.value < 768;
      };
    
      onMounted(() => window.addEventListener('resize', update));
      onUnmounted(() => window.removeEventListener('resize', update));
    
      return { width, isMobile };
    }
    

    8. Performance Best Practices for Scale

    1. Code Splitting: As shown in the Router section, use dynamic imports () => import(...) for routes. This ensures Vite splits the code into chunks.
    2. Lazy Components: Use defineAsyncComponent for heavy UI elements (like a rich text editor or charts) that aren't immediately visible.
    3. Virtual Scrolling: If displaying lists > 1000 items, install @vueuse/core and use useVirtualList.

    9. Testing Strategy

    A large app cannot survive without tests.

    1. Unit (Vitest): Test logic in Composables, Stores, and Helpers.
    2. Component (Vitest + Vue Test Utils): Test props, events, and slot rendering.
    3. E2E (Cypress or Playwright): Test critical User Flows (Login -> Add to Cart -> Checkout).

    Example Unit Test (productStore.spec.ts):

    import { setActivePinia, createPinia } from 'pinia';
    import { useProductStore } from '@/modules/products/store/productStore';
    import { describe, it, expect, beforeEach, vi } from 'vitest';
    
    describe('Product Store', () => {
      beforeEach(() => {
        setActivePinia(createPinia());
      });
    
      it('fetches products', async () => {
        const store = useProductStore();
        // Mock API here
        await store.fetchProducts();
        expect(store.products.length).toBeGreaterThan(0);
      });
    });
    

    Summary of Key Scalability Concepts Used:

    1. Colocation: Logic, views, and types are grouped by Feature (Module), not by file type.
    2. Strict Typing: No any. Interfaces for Props, API responses, and Store state.
    3. Logic Reuse: Logic is extracted from components into Composables (use...) or Stores.
    4. Lazy Loading: Routes are lazy-loaded by default to keep the initial bundle size small.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.