---
# === IDENTITY ===
id: software/devops/vite-configuration/2026
canonical_question: "Vite configuration reference"
aliases:
  - "How to configure vite.config.ts for production"
  - "Vite build and dev server configuration guide"
  - "vite.config.ts best practices and options"
  - "Vite proxy, aliases, and plugin setup reference"
entity_type: software_reference
domain: software > devops > Vite Configuration
region: global
jurisdiction: global
temporal_scope: 2024-2026

# === VERIFICATION ===
last_verified: 2026-02-28
confidence: 0.93
version: 1.0
first_published: 2026-02-28

# === TEMPORAL VALIDITY ===
temporal_validity:
  status: stable
  last_breaking_change: "Vite 6.0 (November 2025) — Environment API, default values changed"
  next_review: 2026-08-27
  change_sensitivity: medium

# === CONSTRAINTS ===
constraints:
  - "vite.config.ts must use defineConfig for type safety and IDE support — raw object exports lose autocomplete"
  - "server.proxy only works during dev — production requires a real reverse proxy or API gateway"
  - "build.target defaults to 'modules' (ES2020) — set explicitly if you need broader browser support"
  - "isolatedModules: true is required in tsconfig.json when using Vite — Vite transpiles each file independently"
  - "Environment variables must be prefixed with VITE_ to be exposed to client code — unprefixed vars are server-only"

# === SKIP CONDITIONS ===
skip_this_unit_if:
  - condition: "Using Next.js (has its own build system)"
    use_instead: "Next.js configuration docs at nextjs.org/docs/app/api-reference/config/next-config-js"
  - condition: "Using webpack and not migrating to Vite"
    use_instead: "webpack configuration docs at webpack.js.org/configuration"

# === AGENT HINTS ===
inputs_needed:
  - key: "framework"
    question: "Which frontend framework are you using?"
    type: choice
    options: ["React", "Vue", "Svelte", "Solid", "Vanilla"]
  - key: "ssr"
    question: "Do you need server-side rendering (SSR)?"
    type: boolean
  - key: "library_mode"
    question: "Are you building a library (not an app)?"
    type: boolean

# === DISTRIBUTION ===
canonical_source: "https://knowledgelib.io/software/devops/vite-configuration/2026"
suggested_citation: "Source: knowledgelib.io — AI Knowledge Library (verified 2026-02-28)"

# === RELATED UNITS ===
related_kos:
  depends_on:
    - id: "software/devops/typescript-tsconfig/2026"
      label: "TypeScript tsconfig Patterns Reference"
  related_to:
    - id: "software/devops/eslint-prettier-config/2026"
      label: "ESLint + Prettier Configuration Reference"
    - id: "software/devops/jest-configuration/2026"
      label: "Jest Testing Configuration Reference"
  solves: []
  alternative_to: []
  often_confused_with: []

# === SOURCES ===
sources:
  - id: src1
    title: "Configuring Vite — Official Documentation"
    author: Vite
    url: https://vite.dev/config/
    type: official_docs
    published: 2025-11-01
    reliability: authoritative
  - id: src2
    title: "Server Options — Vite"
    author: Vite
    url: https://vite.dev/config/server-options
    type: official_docs
    published: 2025-11-01
    reliability: authoritative
  - id: src3
    title: "Build Options — Vite"
    author: Vite
    url: https://vite.dev/config/build-options
    type: official_docs
    published: 2025-11-01
    reliability: authoritative
  - id: src4
    title: "Features — Vite"
    author: Vite
    url: https://vite.dev/guide/features
    type: official_docs
    published: 2025-11-01
    reliability: authoritative
  - id: src5
    title: "Environment API — Vite"
    author: Vite
    url: https://main.vite.dev/guide/api-environment
    type: official_docs
    published: 2025-11-01
    reliability: high
  - id: src6
    title: "Configuring Vitest"
    author: Vitest
    url: https://vitest.dev/config/
    type: official_docs
    published: 2025-01-01
    reliability: high
  - id: src7
    title: "vite-tsconfig-paths — npm"
    author: Alec Larson
    url: https://www.npmjs.com/package/vite-tsconfig-paths
    type: community_resource
    published: 2025-01-01
    reliability: moderate_high
---

# Vite Configuration Reference

## TL;DR

- **Bottom line**: Use `defineConfig` in `vite.config.ts` for type-safe configuration; key areas are `plugins` (framework adapters), `resolve.alias` (path shortcuts), `server.proxy` (dev API proxy), and `build.rollupOptions` (production output tuning).
- **Key tool/command**: `npx vite` (dev) / `npx vite build` (production) / `npx vite preview` (preview production build)
- **Watch out for**: Using `server.proxy` and expecting it to work in production — it is dev-server only; production needs Nginx/Caddy/Cloudflare.
- **Works with**: Vite 5.x–6.x, Node.js 18+, React, Vue, Svelte, Solid, Vanilla JS/TS.

## Constraints
<!-- Agents: read this section before recommending any action from this unit.
     These are hard constraints that must not be violated. -->

- `vite.config.ts` must use `defineConfig` for type safety and IDE support — raw object exports lose autocomplete
- `server.proxy` only works during dev — production requires a real reverse proxy or API gateway
- `build.target` defaults to `"modules"` (ES2020) — set explicitly if you need broader browser support
- `isolatedModules: true` is required in `tsconfig.json` when using Vite — Vite transpiles each file independently
- Environment variables must be prefixed with `VITE_` to be exposed to client code — unprefixed vars are server-only

## Quick Reference

| Option | Default | Purpose |
|---|---|---|
| `root` | `process.cwd()` | Project root directory |
| `base` | `"/"` | Public base path (set for subdirectory deploys) |
| `plugins` | `[]` | Framework adapters and transforms |
| `resolve.alias` | `{}` | Path alias mapping (`@` → `./src`) |
| `server.port` | `5173` | Dev server port |
| `server.proxy` | `{}` | API proxy for dev (NOT production) |
| `server.open` | `false` | Auto-open browser on start |
| `server.cors` | `true` | Enable CORS in dev |
| `build.outDir` | `"dist"` | Production output directory |
| `build.target` | `"modules"` | Browser target for production |
| `build.sourcemap` | `false` | Generate source maps |
| `build.rollupOptions` | `{}` | Advanced Rollup config (chunking, externals) |
| `build.minify` | `"esbuild"` | Minifier (`"esbuild"` or `"terser"`) |
| `optimizeDeps.include` | `[]` | Force pre-bundle specific dependencies |
| `css.modules` | auto-detected | CSS Modules configuration |
| `envPrefix` | `"VITE_"` | Prefix for client-exposed env vars |

## Decision Tree

```
START
├── React project?
│   ├── YES → plugin: @vitejs/plugin-react (Babel) or @vitejs/plugin-react-swc (faster)
│   └── NO ↓
├── Vue project?
│   ├── YES → plugin: @vitejs/plugin-vue
│   └── NO ↓
├── Svelte project?
│   ├── YES → plugin: @sveltejs/vite-plugin-svelte
│   └── NO ↓
├── Building a library?
│   ├── YES → Use build.lib mode with rollupOptions.external
│   └── NO ↓
├── Need SSR?
│   ├── YES → Configure build.ssr + server middleware
│   └── NO ↓
├── Need API proxy in dev?
│   ├── YES → Configure server.proxy
│   └── NO ↓
└── DEFAULT → defineConfig with resolve.alias + build defaults
```

## Step-by-Step Guide

### 1. Create vite.config.ts

Initialize with `defineConfig` and your framework plugin. [src1]

```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig({
  plugins: [react()],
});
```

**Verify**: `npx vite --version` → `vite/6.x.x`

### 2. Configure path aliases

Set up `@` alias to avoid deep relative imports. Must match tsconfig `paths`. [src1]

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import path from 'node:path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@utils': path.resolve(__dirname, 'src/utils'),
    },
  },
});
```

**Verify**: Import `@/App` in a file → no build errors

### 3. Set up dev server proxy

Proxy API requests to a backend during development. [src2]

```typescript
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        // Optional: rewrite path
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
      '/ws': {
        target: 'ws://localhost:8080',
        ws: true,
      },
    },
  },
});
```

**Verify**: `npx vite` → `fetch('/api/health')` hits `localhost:8080/health`

### 4. Configure production build

Optimize output for production deployment. [src3]

```typescript
export default defineConfig({
  plugins: [react()],
  build: {
    target: 'es2022',
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
        },
      },
    },
  },
});
```

**Verify**: `npx vite build && ls dist/assets/` → separate `vendor-*.js` and `router-*.js` chunks

### 5. Configure environment variables

Define env variables with the `VITE_` prefix for client access. [src4]

```bash
# .env
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App
DATABASE_URL=postgresql://...  # NOT exposed to client (no VITE_ prefix)
```

```typescript
// In your code:
const apiUrl = import.meta.env.VITE_API_URL;
const mode = import.meta.env.MODE;  // 'development' or 'production'
const isDev = import.meta.env.DEV;  // boolean
```

**Verify**: `npx vite` → `console.log(import.meta.env.VITE_API_URL)` prints the value

### 6. Configure conditional settings per mode

Use function syntax for mode-dependent config. [src1]

```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

export default defineConfig(({ command, mode }) => {
  const isProduction = mode === 'production';

  return {
    plugins: [react()],
    build: {
      sourcemap: !isProduction,
      minify: isProduction ? 'esbuild' : false,
    },
    server: {
      open: command === 'serve',
    },
  };
});
```

**Verify**: `npx vite build --mode production` → no sourcemaps in output

## Code Examples

### Complete Vite + React + TypeScript config

> Full script: [complete-vite-react-typescript-config.ts](scripts/complete-vite-react-typescript-config.ts) (42 lines)

```typescript
// vite.config.ts — full production-ready React config
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'node:path';
# ... (see full script)
```

### Vite library mode config

```typescript
// vite.config.ts — npm library build
import { defineConfig } from 'vite';
import { resolve } from 'node:path';
import dts from 'vite-plugin-dts';

export default defineConfig({
  plugins: [dts({ rollupTypes: true })],
  build: {
    lib: {
      entry: resolve(__dirname, 'src/index.ts'),
      name: 'MyLib',
      formats: ['es', 'cjs'],
      fileName: (format) => `index.${format === 'es' ? 'mjs' : 'cjs'}`,
    },
    rollupOptions: {
      external: ['react', 'react-dom'],
      output: {
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
        },
      },
    },
  },
});
```

### Vite + Vue 3 config

```typescript
// vite.config.ts — Vue 3 project
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import path from 'node:path';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  server: {
    port: 3000,
  },
  build: {
    target: 'es2022',
  },
});
```

## Anti-Patterns

### Wrong: Expecting server.proxy in production

```typescript
// ❌ BAD — proxy only works in dev; production build is static
export default defineConfig({
  server: {
    proxy: { '/api': 'http://api-server:8080' },
  },
  // Deploying dist/ to CDN — proxy is gone!
});
```

### Correct: Use proxy for dev, real reverse proxy for production

```typescript
// ✅ GOOD — dev proxy + production env variable
export default defineConfig({
  server: {
    proxy: { '/api': 'http://localhost:8080' },
  },
});
// In production code: const API = import.meta.env.VITE_API_URL || '/api';
// In production: configure Nginx/Caddy to proxy /api to backend
```

### Wrong: Not using defineConfig

```typescript
// ❌ BAD — no type safety, no autocomplete
export default {
  plugins: [],
  sever: { port: 3000 },  // Typo not caught!
};
```

### Correct: Always use defineConfig

```typescript
// ✅ GOOD — type errors caught immediately
import { defineConfig } from 'vite';
export default defineConfig({
  plugins: [],
  server: { port: 3000 },  // Typo "sever" would be a TS error
});
```

### Wrong: Exposing secrets via VITE_ prefix

```typescript
// ❌ BAD — VITE_ vars are bundled into client JS, visible to anyone
// .env
// VITE_DATABASE_URL=postgresql://user:password@host/db
// VITE_SECRET_KEY=sk_live_abc123
```

### Correct: Only prefix public values with VITE_

```bash
# ✅ GOOD — only public values get VITE_ prefix
# .env
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App
DATABASE_URL=postgresql://...        # Server-only, not exposed
SECRET_KEY=sk_live_abc123            # Server-only, not exposed
```

## Common Pitfalls

- **Port already in use**: Dev server fails to start. Fix: use `server: { strictPort: true }` to fail fast, or `server: { port: 0 }` for auto-assign. [src2]
- **Path aliases not resolved**: Aliases defined in `resolve.alias` but not in `tsconfig.json`. Fix: use `vite-tsconfig-paths` plugin to auto-sync, or define in both places. [src7]
- **CSS modules not working**: File not named `*.module.css`. Fix: Vite auto-detects CSS Modules from `.module.css`/`.module.scss` filename convention. [src4]
- **Dependency pre-bundling issues**: A library uses CJS internally and breaks in dev. Fix: add to `optimizeDeps.include: ['problem-lib']` to force pre-bundling. [src1]
- **Build output too large**: All vendor code in one chunk. Fix: use `build.rollupOptions.output.manualChunks` to split vendors. [src3]
- **Environment variables undefined**: Var not prefixed with `VITE_`. Fix: rename to `VITE_MY_VAR` or access via `process.env` in server-side code only. [src4]

## Diagnostic Commands

```bash
# Check Vite version
npx vite --version

# Start dev server with debug logging
npx vite --debug

# Preview production build locally
npx vite preview

# Analyze bundle size
npx vite build && npx vite-bundle-visualizer

# List resolved config
npx vite --debug config

# Check for dependency optimization issues
npx vite optimize --force
```

## Version History & Compatibility

| Version | Status | Breaking Changes | Migration Notes |
|---|---|---|---|
| Vite 6.x | Current | Environment API (experimental), default value changes | Most configs work unchanged from v5 |
| Vite 5.x | Maintenance | Rollup 4, Node 18+ required | Update Rollup plugins if using custom ones |
| Vite 4.x | EOL | SWC-based React plugin default | Upgrade `@vitejs/plugin-react-swc` |
| Vite 3.x | EOL | — | Migrate to v5+ for security patches |

## When to Use / When Not to Use

| Use When | Don't Use When | Use Instead |
|---|---|---|
| New React/Vue/Svelte/Solid apps | Next.js or Nuxt projects (own build system) | Framework CLI |
| Need fast dev server with HMR | Building for very old browsers (IE11) | webpack 5 |
| Library bundling for npm | Server-only Node.js project | tsc or esbuild directly |
| Replacing CRA or webpack starter | Already on Turbopack and satisfied | Turbopack |

## Important Caveats

- Vite 6's Environment API is experimental and not yet recommended for wide adoption — most users should stick with standard config
- `server.proxy` uses `http-proxy` under the hood — complex proxy scenarios may need `configure` callback for custom middleware
- `build.target: "esnext"` produces the smallest bundles but requires all users on very modern browsers
- Worker scripts need separate config via `worker.format` and `worker.plugins` — they do not inherit main config plugins

## Related Units

- [TypeScript tsconfig Patterns Reference](/software/devops/typescript-tsconfig/2026)
- [ESLint + Prettier Configuration Reference](/software/devops/eslint-prettier-config/2026)
- [Jest Testing Configuration Reference](/software/devops/jest-configuration/2026)
