> ## Documentation Index
> Fetch the complete documentation index at: https://docs.weventures.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Vite

> Lightning-fast build tool for modern web development

## What is Vite?

<Tabs>
  <Tab title="For Beginners">
    Vite (pronounced "veet", French for "fast") is a **build tool** that helps you develop web applications quickly. Here's what it does:

    * **Development Server**: Starts your app instantly (no waiting!) and updates immediately when you save changes
    * **Build Tool**: Bundles your code for production, making it fast and optimized for users
    * **Modern Approach**: Uses native ES modules in development for lightning-fast hot reloading

    **Think of it this way:**

    * Traditional tools (like Webpack) rebuild your entire app on every change → slow
    * Vite only rebuilds what changed → instant updates

    **Key benefits for learners:**

    * Starts in milliseconds, not seconds
    * Works with React, Vue, or vanilla JavaScript
    * Simple configuration (or none at all!)
    * Great for learning because you see changes instantly
  </Tab>

  <Tab title="Why We Use It">
    Vite provides the fastest development experience with modern ESM-based architecture. We use it for projects that need maximum developer velocity without the complexity of full-stack frameworks.
  </Tab>
</Tabs>

<CardGroup cols={3}>
  <Card title="Instant Server" icon="bolt">
    Starts dev server in milliseconds with native ESM
  </Card>

  <Card title="Hot Module Replacement" icon="fire">
    Lightning-fast updates without losing app state
  </Card>

  <Card title="Optimized Builds" icon="box">
    Production builds with Rollup for optimal performance
  </Card>
</CardGroup>

## When to Use

<Tabs>
  <Tab title="Perfect For">
    * Single-page applications (SPAs)
    * Client-side only apps
    * Prototypes and MVPs
    * Component libraries
    * Static web apps
    * Learning React/Vue
  </Tab>

  <Tab title="Use Next.js Instead">
    * SEO is critical (need server-side rendering)
    * Full-stack applications with API routes
    * Authentication flows requiring server middleware
    * E-commerce with dynamic content
  </Tab>
</Tabs>

## Project Setup

<Steps>
  <Step title="Create New Project">
    ```bash theme={null}
    # With React
    pnpm create vite@latest my-app -- --template react-ts

    # With Vue
    pnpm create vite@latest my-app -- --template vue-ts

    # Vanilla TypeScript
    pnpm create vite@latest my-app -- --template vanilla-ts
    ```
  </Step>

  <Step title="Install Dependencies">
    ```bash theme={null}
    cd my-app
    pnpm install
    ```
  </Step>

  <Step title="Start Development">
    ```bash theme={null}
    pnpm dev
    ```
  </Step>
</Steps>

## Best Practices

### File Structure

```
src/
├── assets/
│   └── images/
├── components/
│   ├── ui/
│   └── features/
├── hooks/
├── lib/
│   └── utils.ts
├── styles/
│   └── main.css
├── App.tsx
└── main.tsx
```

### Configuration

<CodeGroup>
  ```typescript vite.config.ts theme={null}
  import { defineConfig } from 'vite'
  import react from '@vitejs/plugin-react'
  import path from 'path'

  export default defineConfig({
    plugins: [react()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    server: {
      port: 3000,
      open: true
    },
    build: {
      outDir: 'dist',
      sourcemap: true
    }
  })
  ```

  ```json tsconfig.json theme={null}
  {
    "compilerOptions": {
      "target": "ES2020",
      "module": "ESNext",
      "lib": ["ES2020", "DOM", "DOM.Iterable"],
      "jsx": "react-jsx",
      "strict": true,
      "moduleResolution": "bundler",
      "resolveJsonModule": true,
      "isolatedModules": true,
      "esModuleInterop": true,
      "noEmit": true,
      "noUncheckedIndexedAccess": true,
      "paths": {
        "@/*": ["./src/*"]
      }
    },
    "include": ["src"]
  }
  ```
</CodeGroup>

### Essential Packages

```bash theme={null}
# UI Framework
pnpm add react react-dom
pnpm add -D @types/react @types/react-dom

# Routing
pnpm add react-router-dom

# Data Fetching
pnpm add @tanstack/react-query axios

# State Management
pnpm add zustand

# Styling
pnpm add tailwindcss postcss autoprefixer
pnpm add -D @tailwindcss/forms @tailwindcss/typography
```

## Common Patterns

### React Router Setup

```tsx theme={null}
// main.tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>
)
```

```tsx theme={null}
// App.tsx
import { Routes, Route } from 'react-router-dom'
import HomePage from './pages/Home'
import AboutPage from './pages/About'

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<HomePage />} />
      <Route path="/about" element={<AboutPage />} />
    </Routes>
  )
}
```

### Environment Variables

<CodeGroup>
  ```bash .env theme={null}
  VITE_API_URL=https://api.example.com
  VITE_APP_TITLE=My App
  ```

  ```tsx Usage theme={null}
  const apiUrl = import.meta.env.VITE_API_URL
  const appTitle = import.meta.env.VITE_APP_TITLE

  // Type-safe env variables
  interface ImportMetaEnv {
    readonly VITE_API_URL: string
    readonly VITE_APP_TITLE: string
  }
  ```
</CodeGroup>

<Warning>
  Environment variables in Vite must be prefixed with `VITE_` to be exposed to client code. Never expose sensitive secrets in client-side code!
</Warning>

### Code Splitting

```tsx theme={null}
import { lazy, Suspense } from 'react'

// Lazy load components
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Settings = lazy(() => import('./pages/Settings'))

export default function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/settings" element={<Settings />} />
      </Routes>
    </Suspense>
  )
}
```

## Performance Optimization

<Accordion title="Asset Optimization">
  ```tsx theme={null}
  // Import images as URLs
  import logoUrl from './assets/logo.png'

  // Import images as modules
  import logo from './assets/logo.png?url'

  // Import as raw string
  import svg from './assets/icon.svg?raw'

  // Explicit URL with query
  <img src={logoUrl} alt="Logo" />
  ```
</Accordion>

<Accordion title="Build Optimization">
  ```typescript theme={null}
  // vite.config.ts
  export default defineConfig({
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            'react-vendor': ['react', 'react-dom'],
            'router': ['react-router-dom'],
            'query': ['@tanstack/react-query']
          }
        }
      },
      chunkSizeWarningLimit: 1000
    }
  })
  ```
</Accordion>

<Accordion title="Preview Production Build">
  ```bash theme={null}
  # Build for production
  pnpm build

  # Preview production build locally
  pnpm preview
  ```
</Accordion>

## Deployment

<CardGroup cols={2}>
  <Card title="Vercel" icon="triangle">
    ```bash theme={null}
    # Auto-detected, zero config
    vercel
    ```
  </Card>

  <Card title="Netlify" icon="leaf">
    ```toml theme={null}
    # netlify.toml
    [build]
      command = "pnpm build"
      publish = "dist"
    ```
  </Card>

  <Card title="GitHub Pages" icon="github">
    ```typescript theme={null}
    // vite.config.ts
    export default defineConfig({
      base: '/repo-name/'
    })
    ```
  </Card>

  <Card title="Railway" icon="train">
    ```bash theme={null}
    # Build and serve static files
    railway up
    ```
  </Card>
</CardGroup>

## Vite vs Next.js

| Feature          | Vite             | Next.js           |
| ---------------- | ---------------- | ----------------- |
| **Dev Speed**    | ⚡ Instant        | Fast              |
| **SSR/SSG**      | ❌ No             | ✅ Yes             |
| **API Routes**   | ❌ No             | ✅ Yes             |
| **File Routing** | ❌ No             | ✅ Yes             |
| **Build Tool**   | ✅ Rollup         | Webpack/Turbopack |
| **Best For**     | SPAs, Prototypes | Full-stack apps   |

<Tip>
  Start with Vite for learning and prototypes. Graduate to Next.js when you need SSR, API routes, or SEO optimization.
</Tip>
