Create React App with Vite
Vite is the fastest way to scaffold a professional React project in 2025. In this chapter you'll
go beyond a simple npm create vite and learn to
customise vite.config.js, add essential
plugins, configure TypeScript, set up
Tailwind CSS, create path aliases, configure
environment variables, and build & preview a production
bundle — all from scratch, step by step.
@/ instead of ../../
.env files with
Vite
1. Scaffold a New React + Vite Project
Vite provides an interactive scaffolding wizard via npm create vite.
You choose the framework (React) and the variant (JavaScript or TypeScript) in a single command.
There are three ways to run it:
# Prompts you to pick # framework + variant $ npm create vite@latest # ✔ Project name: … # ✔ Framework: React # ✔ Variant: JavaScript
# Skip prompts — JS app $ npm create vite@latest \ my-app -- --template react
# Skip prompts — TS app $ npm create vite@latest \ my-app -- --template react-ts
After scaffolding, run these three commands to install and start:
$ cd my-app
$ npm install # downloads node_modules (first-time setup)
$ npm run dev # starts local dev server
# Expected output:
VITE v5.x.x ready in 218 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h + enter to show helpvite@latest?
Always use @latest to get the newest stable Vite. Without
it,
npm may use a cached older version. As of 2025, Vite 5 is stable — always check
vitejs.dev for the current release.
Vite supports multiple templates. Here are all the React-relevant ones:
| Template flag | Language | Includes | Use when |
|---|---|---|---|
react |
JavaScript | JSX, HMR, ESLint | Most beginner projects ✅ |
react-ts |
TypeScript | TSX, tsconfig, HMR, ESLint | Production / team projects ✅ |
react-swc |
JavaScript | SWC compiler (faster than Babel) | Large codebases needing speed |
react-swc-ts |
TypeScript | SWC + TS — fastest possible | Large TS projects |
2. Understanding vite.config.js
vite.config.js (or vite.config.ts) is the
single configuration file that controls everything Vite does — dev server, build output,
plugins, aliases, and more. Let's look at a well-commented production-ready config:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
export default defineConfig({
/* ─── Plugins ─────────────────────────────────────── */
plugins: [react()], // enables JSX transform + Fast Refresh
/* ─── Dev server options ──────────────────────────── */
server: {
port: 5173, // default port (change if busy)
open: true, // auto-open browser on npm run dev
strictPort: false, // try next port if 5173 is taken
host: true, // expose to LAN (useful for mobile testing)
},
/* ─── Path aliases ─────────────────────────────────── */
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
// import Button from '@/components/Button'
},
},
/* ─── Build options ────────────────────────────────── */
build: {
outDir: 'dist', // output folder (default)
sourcemap: false, // true for debugging production
minify: 'esbuild', // 'esbuild' (fast) or 'terser' (smaller)
chunkSizeWarningLimit: 800, // warn if chunk > 800kB
},
/* ─── CSS options ──────────────────────────────────── */
css: {
devSourcemap: true, // CSS source maps in dev
},
})Here's a breakdown of every top-level key you'll commonly use:
| Key | Purpose | Common values |
|---|---|---|
plugins |
Array of Vite plugins to load | react(), svgr() |
server.port |
Dev server port | 5173 (default) |
server.open |
Auto-open browser on start | true / false |
resolve.alias |
Import path shortcuts | { '@': './src' } |
build.outDir |
Production output folder | 'dist' (default) |
build.sourcemap |
Generate source maps | true / false |
build.minify |
Minification engine | 'esbuild' or 'terser' |
base |
Public base path for deployment | '/' or '/my-app/' |
defineConfig({}). It provides
full TypeScript type inference and IDE autocompletion — even when using the .js file extension.
3. Vite Plugins for React Projects
Vite's plugin system extends its capabilities. The core React plugin is mandatory — the others solve common real-world needs. Install only what your project actually needs.
import {ReactComponent as Logo} from './logo.svg'
— same as CRA.tsconfig.json automatically. No need to duplicate
aliases in both vite.config.ts and tsconfig.json./__inspect. See exactly how each file is
transformed by every plugin. Great for debugging the build pipeline.npm run build. Essential for identifying large
dependencies and code-split opportunities.Here's how a typical vite.config.js
looks with multiple plugins wired together:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
import { visualizer } from 'rollup-plugin-visualizer'
export default defineConfig({
plugins: [
react(), // JSX + Fast Refresh
svgr(), // import SVG as React components
visualizer({ // bundle size treemap
open: true, // auto-open after build
filename: 'dist/stats.html',
}),
],
})4. TypeScript Setup with Vite + React
TypeScript adds static type-checking to your React code — catching bugs at edit time
rather than at runtime. Vite's react-ts template
configures everything automatically. Let's explore the key files:
$ npm create vite@latest my-ts-app -- --template react-ts
$ cd my-ts-app && npm install && npm run devThe generated tsconfig.json — and what each key does:
{
"compilerOptions": {
"target": "ES2020", // compile to ES2020 syntax
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext", // use ES module imports
"skipLibCheck": true, // skip type-checking .d.ts files
/* ─── Bundler mode ─── */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true, // import .json files
"isolatedModules": true, // each file compiled independently
"noEmit": true, // Vite handles emitting, not tsc
/* ─── React ─── */
"jsx": "react-jsx", // use new JSX transform (no React import needed)
/* ─── Strict mode ─── */
"strict": true, // all strict checks on — recommended
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
/* ─── Path aliases ─── */
"baseUrl": ".",
"paths": { "@/*": ["./src/*"] }
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}A typed React component example with props interface:
interface ButtonProps {
label: string
variant?: 'primary' | 'outline' | 'ghost'
disabled?: boolean
onClick?: () => void
}
function Button({ label, variant = 'primary', disabled = false, onClick }: ButtonProps) {
return (
<button
className={`btn btn-${variant}`}
disabled={disabled}
onClick={onClick}
>
{label}
</button>
)
}
export default Buttonreact-ts
template is a good habit.
TypeScript catches props mismatches, undefined errors and refactoring mistakes before they hit
the browser.
The strict: true setting is your safety net.
5. Add Tailwind CSS to a Vite + React Project
Tailwind CSS is the most popular utility-first CSS framework for React in 2025. Here's the complete installation flow for a Vite project — it takes under 2 minutes:
tailwind.config.js and postcss.config.js$ npm install -D tailwindcss postcss autoprefixer
$ npx tailwindcss init -p # generates tailwind.config.js + postcss.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}", // scan all JS/TS/JSX/TSX files
],
theme: {
extend: {}, // add custom colours, fonts, spacing here
},
plugins: [],
}/* Replace the entire content of index.css with these 3 lines */
@tailwind base;
@tailwind components;
@tailwind utilities;Now use Tailwind classes directly in JSX:
function Hero() {
return (
<section className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="text-center px-6">
<h1 className="text-5xl font-bold text-white mb-4">
Hello, Tailwind! 🎨
</h1>
<p className="text-gray-400 text-lg max-w-md mx-auto">
Utility-first CSS inside Vite + React
</p>
<button className="mt-8 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-semibold transition">
Get Started
</button>
</div>
</section>
)
}6. Path Aliases — Use @/
Instead of ../../
As your project grows, relative import paths get long and fragile:
import Button from '../../../components/ui/Button'.
Path aliases let you write import Button from '@/components/ui/Button'
from anywhere in your project. You configure the alias in two places:
// Inside src/pages/dashboard/Overview.jsx import Button from '../../../components/ui/Button' import useAuth from '../../hooks/useAuth' import api from '../../services/api' import Logo from '../../../assets/logo.svg'
@ alias (clean)
// Same file — same imports, much cleaner import Button from '@/components/ui/Button' import useAuth from '@/hooks/useAuth' import api from '@/services/api' import Logo from '@/assets/logo.svg'
Configure the alias in both vite.config.js and tsconfig.json (if using TypeScript):
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'),
'@hooks': path.resolve(__dirname, './src/hooks'),
'@assets': path.resolve(__dirname, './src/assets'),
},
},
}){
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@components/*": ["./src/components/*"],
"@hooks/*": ["./src/hooks/*"],
"@assets/*": ["./src/assets/*"]
}
}
}vite.config.js handle the runtime
bundling.
The aliases in tsconfig.json handle the TypeScript
language
server (IDE autocompletion). You need both to work together.
7. Environment Variables in Vite
Environment variables store sensitive config like API keys and base URLs outside your code.
Vite uses .env files and exposes them via
import.meta.env — not process.env
like Node.js or CRA.
VITE_ are exposed to the
browser.
Any variable without this prefix is only available server-side and will NOT appear
in your client bundle. Never put secret keys in VITE_ variables — they are visible in the browser.
# .env — loaded always # .env.local — ignored by git # .env.development — dev only # .env.production — production only # .env.test — test mode # More specific = higher priority # .env.local overrides .env
# Exposed to browser (VITE_ prefix) VITE_API_URL=https://api.example.com VITE_APP_NAME=My React App VITE_GOOGLE_MAPS_KEY=AIza... # NOT exposed to browser (no prefix) DATABASE_URL=postgres://... SECRET_KEY=super_secret_123
function App() {
// Access VITE_ prefixed env vars
const apiUrl = import.meta.env.VITE_API_URL
const appName = import.meta.env.VITE_APP_NAME
// Vite's built-in env vars (always available)
const isDev = import.meta.env.DEV // true in dev mode
const isProd = import.meta.env.PROD // true in production
const mode = import.meta.env.MODE // 'development' | 'production'
const baseUrl = import.meta.env.BASE_URL // the configured base path
return <h1>{appName} — API: {apiUrl}</h1>
}8. Build for Production & Deploy
When your app is ready to ship, Vite's Rollup-powered build pipeline compiles, minifies,
tree-shakes, and code-splits your project into a static
dist/ folder ready for any hosting platform.
# Step 1: Build the production bundle
$ npm run build
vite v5.x.x building for production...
✓ 34 modules transformed.
dist/index.html 0.46 kB
dist/assets/index-Bq1xMUmJ.css 8.12 kB │ gzip: 2.14 kB
dist/assets/index-CQh9yWre.js 142.50 kB │ gzip: 45.79 kB
✓ built in 834ms
# Step 2: Preview the production build locally
$ npm run preview
➜ Local: http://localhost:4173/
# Step 3: Deploy the dist/ folder to any hostThe dist/
folder is a static site — deployable anywhere:
dist/
folder into Netlify. Or connect your GitHub repo for auto-deploy on every push. Free
tier available.vercel deploy or push to
GitHub. Vercel auto-detects Vite and sets build command to npm run build. Free tier available.base: '/repo-name/' in
vite.config.js, build, and push dist/ to the gh-pages branch.
dist/ to any web server
— Apache, Nginx, AWS S3, Firebase Hosting, Render. Just serve the static files.export default defineConfig({
// Set base to your repo name for GitHub Pages
base: '/my-react-app/', // ← replace with your repo name
plugins: [react()],
build: {
outDir: 'dist',
sourcemap: false,
},
})import.meta.env and how is it different from
process.env?
import.meta.env is Vite's way of exposing
environment
variables to the browser. It is part of the ES Module Metadata API and
works in the browser.
process.env is a Node.js global — it doesn't exist
in the browser. CRA shimmed it with webpack, but Vite uses the standards-based
import.meta.env instead.
Only variables prefixed with
VITE_ are injected into
the browser bundle. All other .env variables are
kept server-side only.
vite.config.js
AND tsconfig.json?
- vite.config.js tells the bundler how to resolve
@/at build time. Without this, Vite will throw a "Cannot find module" error. - tsconfig.json paths tells the TypeScript Language
Server (your IDE) how to understand
@/for type-checking and autocompletion. Without this, your editor shows red underlines even though the build works.
@vitejs/plugin-react and
@vitejs/plugin-react-swc?
- plugin-react uses Babel — the JavaScript standard for years. Slower transforms but supports the full Babel ecosystem (plugins and presets).
- plugin-react-swc uses SWC — a Rust-based compiler that is 20× faster than Babel. Recommended for larger projects where HMR speed matters. Does not support Babel-specific plugins.
plugin-react-swc.
npm run preview do in a
Vite project?- Use
npm create vite@latest app -- --template reactto scaffold (orreact-tsfor TypeScript). vite.config.jsis the single config file — wraps indefineConfig({})for type safety.- @vitejs/plugin-react is mandatory; plugin-react-swc is the faster Rust alternative.
- Add Tailwind in 4 steps: install,
init -p, configure content paths, add 3 directives to CSS. - Path alias
@must be configured in bothvite.config.jsandtsconfig.json. - Vite uses
import.meta.env(notprocess.env); onlyVITE_-prefixed vars reach the browser. npm run build→ Rollup bundles todist/. Deploy to Vercel, Netlify or any static host.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.