React with Vite

Lightning-fast React development experience

⚡ What is Vite?

Vite is a modern build tool that provides extremely fast development server startup and hot module replacement for React applications. It uses native ES modules for instant updates without rebuilding the entire application.


# Create React app with Vite
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
                                    

Key Vite Features

Instant Server Start

Dev server starts in milliseconds

npm run dev
# Server ready instantly!
🔥

Hot Module Replacement

Instant updates without page reload

// Changes reflect instantly
export default function App() {}
📦

Optimized Build

Fast production builds with Rollup

npm run build
# Optimized bundle ready
🔌

Plugin System

Extend functionality with plugins

// vite.config.js
plugins: [react()]

🔹 Creating a Vite React App

Create a new React application with Vite using the official scaffolding tool. Choose between JavaScript or TypeScript templates for your project setup.

# Create new Vite React app
npm create vite@latest my-react-app -- --template react

# Or with TypeScript
npm create vite@latest my-react-app -- --template react-ts

# Navigate to project
cd my-react-app

# Install dependencies
npm install

# Start development server
npm run dev

Your app will be running at http://localhost:5173

🔹 Project Structure

Vite creates a clean, minimal project structure. The main files are organized logically with clear separation between source code, public assets, and configuration.

my-react-app/
├── public/          # Static assets
├── src/
│   ├── App.jsx      # Main component
│   ├── App.css      # Component styles
│   ├── main.jsx     # Entry point
│   └── index.css    # Global styles
├── index.html       # HTML template
├── vite.config.js   # Vite configuration
└── package.json     # Dependencies

🔹 Basic React Component

Create React components in Vite just like any React app. Vite handles JSX transformation and hot module replacement automatically for instant feedback during development.

// src/App.jsx
import { useState } from 'react';
import './App.css';

function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <h1>Vite + React</h1>
      <button onClick={() => setCount(count + 1)}>
        Count is: {count}
      </button>
    </div>
  );
}

export default App;

🔹 Importing Assets

Import images, CSS, and other assets directly in your components. Vite handles all asset types and optimizes them automatically during the build process.

// Import CSS
import './App.css';

// Import images
import logo from './assets/logo.png';

// Import JSON
import data from './data.json';

function App() {
  return (
    <div>
      <img src={logo} alt="Logo" />
      <p>{data.message}</p>
    </div>
  );
}

// CSS Modules
import styles from './App.module.css';

function App() {
  return <div className={styles.container}>Hello</div>;
}

🔹 Environment Variables

Use environment variables for configuration and API keys. Vite exposes variables prefixed with VITE_ to your client-side code for secure configuration management.

# .env
VITE_API_URL=https://api.example.com
VITE_APP_TITLE=My App

# .env.production
VITE_API_URL=https://api.production.com
// Access in components
function App() {
  const apiUrl = import.meta.env.VITE_API_URL;
  const appTitle = import.meta.env.VITE_APP_TITLE;
  
  return (
    <div>
      <h1>{appTitle}</h1>
      <p>API: {apiUrl}</p>
    </div>
  );
}

🔹 Vite Configuration

Customize Vite behavior through the configuration file. Add plugins, configure build options, set up proxies, and define aliases for cleaner imports.

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true // Open browser automatically
  },
  build: {
    outDir: 'dist',
    sourcemap: true
  },
  resolve: {
    alias: {
      '@': '/src' // Use @ for src imports
    }
  }
});

// Usage with alias
import Button from '@/components/Button';

🔹 API Proxy Configuration

Configure proxy settings to avoid CORS issues during development. Vite can forward API requests to your backend server seamlessly without additional configuration.

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
});

// Now you can call
fetch('/api/users') // Proxied to http://localhost:8080/users

🔹 Adding CSS Preprocessors

Use Sass, Less, or Stylus by simply installing them. Vite automatically detects and processes these preprocessors without additional configuration needed.

# Install Sass
npm install -D sass

# Install Less
npm install -D less
// Use .scss files directly
import './App.scss';

// App.scss
$primary-color: #3498db;

.app {
  color: $primary-color;
  
  &:hover {
    opacity: 0.8;
  }
}

🔹 Building for Production

Build optimized production bundles with code splitting, minification, and tree shaking. Vite creates highly optimized builds that load fast for end users.

# Build for production
npm run build

# Preview production build locally
npm run preview

Build Output:

  • Minified JavaScript bundles
  • Optimized CSS files
  • Compressed assets
  • Source maps (optional)

🔹 Popular Vite Plugins

Extend Vite functionality with plugins for PWA support, SVG components, legacy browser support, and more. The plugin ecosystem makes Vite highly customizable.

# Install plugins
npm install -D vite-plugin-pwa
npm install -D vite-plugin-svgr
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { VitePWA } from 'vite-plugin-pwa';
import svgr from 'vite-plugin-svgr';

export default defineConfig({
  plugins: [
    react(),
    svgr(), // Import SVGs as React components
    VitePWA({ // PWA support
      registerType: 'autoUpdate',
      manifest: {
        name: 'My App',
        short_name: 'App',
        theme_color: '#ffffff'
      }
    })
  ]
});

🔹 Complete Example

A complete Vite React app with components, styling, and state management. This demonstrates the typical structure and patterns used in Vite projects.

// src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// src/App.jsx
import { useState } from 'react';
import Counter from './components/Counter';
import './App.css';

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <div className={`app ${theme}`}>
      <h1>{import.meta.env.VITE_APP_TITLE}</h1>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
      <Counter />
    </div>
  );
}

export default App;

🧠 Test Your Knowledge

What is the default port for Vite development server?