ViVite · Lesson 2 of 6

Vite Config

`vite.config.ts` is where you configure everything: plugins, path aliases, proxy rules, build options, and environment variables. It's shorter than Webpack config by an order of magnitude.

TypeScript
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'

export default defineConfig({
  // Plugins — framework support, transformations
  plugins: [react()],

  // Path aliases — import '@/components/Button' instead of '../../components/Button'
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
    },
  },

  // Dev server options
  server: {
    port: 3000,
    open: true,     // auto-open browser

    // Proxy API requests to avoid CORS during development
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: path => path.replace(/^/api/, ''),
      },
    },
  },

  // Build options
  build: {
    outDir: 'dist',
    sourcemap: true,
    target: 'es2020',
    // Chunk splitting — separate vendor from app code
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        },
      },
    },
  },

  // CSS handling
  css: {
    modules: {
      localsConvention: 'camelCase',
    },
  },
})
TypeScript
// Environment variables in Vite
// Variables must be prefixed with VITE_ to be exposed to the client

// .env                — loaded in all environments
// .env.local          — loaded in all environments, ignored by git
// .env.development    — loaded in dev only
// .env.production     — loaded in production build only

// .env.local
// VITE_API_URL=http://localhost:8080
// VITE_STRIPE_KEY=pk_test_xxxxx

// Access in your code:
const apiUrl  = import.meta.env.VITE_API_URL
const isProd  = import.meta.env.PROD       // boolean
const isDev   = import.meta.env.DEV        // boolean
const mode    = import.meta.env.MODE       // 'development' | 'production'

// TypeScript: declare the env variables for type safety
// src/env.d.ts
interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_STRIPE_KEY: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
✦ Tip
Never prefix non-public secrets with `VITE_`. Anything with `VITE_` is bundled into your client-side code and visible in the browser. Server-side secrets (database URLs, private API keys) should be in your backend environment, not your frontend .env files.