Tutorials React JS Create React App with Vite
Ch 3 / 46
Chapter 3 Beginner 10 min read React JS

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.

Advertisement
What you'll learn
Scaffold with Vite — JS and TypeScript templates explained
vite.config.js — every option you'll actually use
Vite Plugins — React Fast Refresh, SVG, Images & more
TypeScript setup — tsconfig.json for React projects
Tailwind CSS — install and configure inside Vite
Path aliases — use @/ instead of ../../
Environment variables — .env files with Vite
Build & Preview — production bundle and deployment prep

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:

Interactive
# Prompts you to pick
# framework + variant
$ npm create vite@latest

# ✔ Project name: …
# ✔ Framework: React
# ✔ Variant: JavaScript
One-liner JS
# Skip prompts — JS app

$ npm create vite@latest \
  my-app -- --template react



One-liner TS
# Skip prompts — TS app

$ npm create vite@latest \
  my-app -- --template react-ts



After scaffolding, run these three commands to install and start:

bash — install dependencies & start dev server
$ 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 help
Why vite@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
Instant Cold Start
Vite uses native ES Modules — no bundling before launch. The dev server starts in ~200ms regardless of project size.
HMR — Hot Module Replacement
Edit a component → the browser updates that single module in <50ms. No full page reload; component state is preserved.
Rollup Production Build
In production, Vite bundles with Rollup — highly optimised tree-shaking, code-splitting and asset fingerprinting built in.
Zero-Config Defaults
Works out of the box for JSX, CSS modules, static assets, JSON imports, and Web Workers — no webpack config needed.
Advertisement

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:

js — vite.config.js (annotated, production-ready)
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 Always wrap your config in 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.

@vitejs/plugin-react
npm i @vitejs/plugin-react
Official React plugin. Enables JSX transform, Babel-powered Fast Refresh, and React-specific optimisations. Required for every React + Vite project.
Core — Always Install
@vitejs/plugin-react-swc
npm i @vitejs/plugin-react-swc
Replaces Babel with SWC (Rust compiler). 20× faster transforms. Drop-in replacement for the Babel plugin. Recommended for large projects.
Alternative to Babel plugin
vite-plugin-svgr
npm i vite-plugin-svgr
Import SVG files as React components. Use import {ReactComponent as Logo} from './logo.svg' — same as CRA.
Recommended
vite-tsconfig-paths
npm i vite-tsconfig-paths
Reads path aliases from tsconfig.json automatically. No need to duplicate aliases in both vite.config.ts and tsconfig.json.
TypeScript projects
vite-plugin-inspect
npm i vite-plugin-inspect -D
Dev-only inspector UI at /__inspect. See exactly how each file is transformed by every plugin. Great for debugging the build pipeline.
Dev / Debug
rollup-plugin-visualizer
npm i rollup-plugin-visualizer -D
Generates an interactive treemap of your bundle after npm run build. Essential for identifying large dependencies and code-split opportunities.
Bundle Analysis

Here's how a typical vite.config.js looks with multiple plugins wired together:

js — vite.config.js with multiple plugins
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.9 / 5 rating
🔥 Most Popular at K2infocom · Vadodara
Frontend Development
Complete Masterclass
Master HTML, CSS, JavaScript, React JS, Bootstrap & more. Build 10+ real-world projects. Get certified and job-ready in 3–6 months.
HTML5 & CSS3 JavaScript ES6+ React JS Vite & Webpack Git & GitHub 5+ Projects
2,500+Students Trained
10+Live Projects
3–6Months Duration
100%Placement Support
Advertisement

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:

bash — scaffold TypeScript React project
$ npm create vite@latest my-ts-app -- --template react-ts $ cd my-ts-app && npm install && npm run dev

The generated tsconfig.json — and what each key does:

json — tsconfig.json (annotated)
{ "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:

tsx — src/components/Button.tsx
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 Button
Start with TypeScript Even for personal projects, starting with the react-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:

1
Install packages — Tailwind, PostCSS and Autoprefixer as dev dependencies
↓
2
Initialise config — generate tailwind.config.js and postcss.config.js
↓
3
Configure content paths — tell Tailwind which files to scan for class names
↓
4
Add directives — add the three Tailwind directives to your global CSS file
bash — Step 1: install Tailwind + PostCSS
$ npm install -D tailwindcss postcss autoprefixer $ npx tailwindcss init -p # generates tailwind.config.js + postcss.config.js
js — tailwind.config.js (Step 2 & 3: configure content paths)
/** @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: [], }
css — src/index.css (Step 4: add Tailwind directives)
/* Replace the entire content of index.css with these 3 lines */ @tailwind base; @tailwind components; @tailwind utilities;

Now use Tailwind classes directly in JSX:

jsx — Tailwind utility classes in a React component
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:

Without alias (messy)
// 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'
With @ 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):

js — vite.config.js with @ alias
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'), }, }, })
json — tsconfig.json: matching paths for TypeScript intellisense
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./src/*"], "@components/*": ["./src/components/*"], "@hooks/*": ["./src/hooks/*"], "@assets/*": ["./src/assets/*"] } } }
Important The aliases in 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.

Security Rule Only variables prefixed with 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 files hierarchy
# .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
.env.local example
# 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
jsx — accessing env variables via import.meta.env
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> }
Advertisement

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.

bash — build, preview and inspect output
# 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 host

The dist/ folder is a static site — deployable anywhere:

Netlify
Drag & drop the dist/ folder into Netlify. Or connect your GitHub repo for auto-deploy on every push. Free tier available.
Vercel
Run vercel deploy or push to GitHub. Vercel auto-detects Vite and sets build command to npm run build. Free tier available.
GitHub Pages
Set base: '/repo-name/' in vite.config.js, build, and push dist/ to the gh-pages branch.
Any Static Host
Upload dist/ to any web server — Apache, Nginx, AWS S3, Firebase Hosting, Render. Just serve the static files.
js — vite.config.js for GitHub Pages deployment
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, }, })
Try React + Vite in Your Browser
No installation needed — experiment with Vite-powered React in StackBlitz, the online IDE that runs Vite natively.
Open Vite + React on StackBlitz
Quick Check — Test Your Understanding
Q1. What is import.meta.env and how is it different from process.env?
✅ Answer
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.
Q2. Why do you need to configure path aliases in both vite.config.js AND tsconfig.json?
✅ Answer
They serve two different purposes:
  • 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.
Both must match for a seamless development experience.
Q3. What is the difference between @vitejs/plugin-react and @vitejs/plugin-react-swc?
✅ Answer
Both plugins enable JSX transformation and Fast Refresh for React, but they use different compilers under the hood:
  • 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.
For most projects, either works. For large codebases, choose plugin-react-swc.
Multiple Choice Questions
MCQ 1
Which Vite template creates a React project with TypeScript?
MCQ 2
Which prefix must an environment variable have to be accessible in the browser via Vite?
MCQ 3
What does npm run preview do in a Vite project?
Chapter 3 Summary
  • Use npm create vite@latest app -- --template react to scaffold (or react-ts for TypeScript).
  • vite.config.js is the single config file — wraps in defineConfig({}) 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 both vite.config.js and tsconfig.json.
  • Vite uses import.meta.env (not process.env); only VITE_-prefixed vars reach the browser.
  • npm run build → Rollup bundles to dist/. Deploy to Vercel, Netlify or any static host.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel