Lesson 2 of 6
Vite Config
You'll learn how to use `vite.config.ts` to up plugins, path aliases, a dev-server proxy, build options and .
// 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',
},
},
})// 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
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.