Vite Configuration for a React App
Vite is the dominant build tool for modern React and Vue applications, offering near-instant hot module replacement and optimized production builds. This configuration sets up the React plugin, TypeScript path alias resolution, a development proxy to avoid CORS issues, and build chunking to improve bundle caching. The JSON formatter is helpful for validating the tsconfig paths that must align with the vite.config.ts resolve aliases. Split vendor chunks from application code so browsers can cache stable library code separately.
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'),
'@components': path.resolve(__dirname, './src/components'),
},
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
rewrite: (p) => p.replace(/^\/api/, ''),
},
},
},
build: {
rollupOptions: {
output: {
manualChunks: { vendor: ['react', 'react-dom'] },
},
},
},
});FAQ
- How do I set up path aliases in Vite?
- Configure the alias in resolve.alias in vite.config.ts and add matching paths in tsconfig.json. Both must match for TypeScript to resolve types and Vite to bundle correctly.
- What does the Vite dev proxy do?
- The proxy forwards requests from the Vite dev server to a separate backend server. This avoids CORS issues during development by making the browser think both frontend and API are on the same origin.
- Why split vendor chunks in the build?
- Separating vendor libraries (React, Lodash, etc.) into a separate chunk means that when only your application code changes, users' browsers can use the cached vendor bundle without re-downloading it.
Related Examples
Enabling strict mode in TypeScript activates a collection of checks that catch t...
Prettier Configuration FilePrettier is an opinionated code formatter that removes all debates about style b...
Format a tsconfig.json FileTypeScript configuration files use JSON with comments (JSONC) which some tools r...