How To Set Up a React Project with Vite for Fast Development

In the world of modern web development, speed and efficiency are paramount. Traditional tools like Create React App (CRA) have long been the go-to for bootstrapping React projects, but they often suffer from slow startup times and cumbersome rebuilds as projects scale. Enter Vite—a next-generation build tool designed to address these pain points with a focus on speed, simplicity, and modern tooling.

Vite leverages native ES modules (ESM) in development to avoid bundling altogether, enabling near-instant server startup and lightning-fast Hot Module Replacement (HMR). For production, it uses Rollup for optimized bundling, ensuring small, efficient outputs. This combination makes Vite an ideal choice for React development, whether you’re building a small app or a large-scale application.

In this guide, we’ll walk through setting up a React project with Vite, exploring its core features, best practices, and advanced configurations to supercharge your development workflow.

Table of Contents#

  1. Prerequisites
  2. Step-by-Step Setup: Creating a Vite + React Project
  3. Understanding the Project Structure
  4. Development Workflow: HMR, Scripts, and Live Reload
  5. Best Practices for Vite + React Development
  6. Advanced Configuration: Customizing Vite
  7. Troubleshooting Common Issues
  8. References

Prerequisites#

Before getting started, ensure you have the following tools installed:

  • Node.js: Vite requires Node.js version 14.18.0 or higher (LTS recommended). Download it from nodejs.org.
  • npm or Yarn: Node.js includes npm by default, but you can use Yarn (v1 or v2+) if preferred.
  • Code Editor: We recommend VS Code with extensions like ESLint, Prettier, and React Developer Tools for a smoother experience.

Step-by-Step Setup: Creating a Vite + React Project#

Vite provides a simple command-line interface (CLI) to scaffold projects. Follow these steps to create a new React project:

1. Scaffold the Project#

Open your terminal and run the following command. Vite will prompt you to select a framework and variant:

npm create vite@latest my-react-vite-app
  • Replace my-react-vite-app with your project name (e.g., portfolio, e-commerce).
  • You’ll see a prompt like this:
✔ Select a framework: › React  
✔ Select a variant: › JavaScript (or TypeScript, SWC, etc.)  

Options Explained:

  • Framework: Choose React.
  • Variant:
    • JavaScript: Basic React with JavaScript.
    • TypeScript: React with TypeScript (recommended for type safety).
    • JavaScript + SWC/TypeScript + SWC: Uses the SWC compiler (faster than Babel for development).

2. Navigate to the Project Directory#

Once the project is scaffolded, move into the directory:

cd my-react-vite-app

3. Install Dependencies#

Install the project dependencies using npm or Yarn:

# Using npm
npm install
 
# Using Yarn
yarn install

4. Start the Development Server#

Run the development server to launch your app:

# Using npm
npm run dev
 
# Using Yarn
yarn dev

Vite will start a local server (usually at http://localhost:5173). Open this URL in your browser—you’ll see the default Vite + React starter page:

Vite React Starter Page

Note: The port (5173) may vary if it’s in use. Check the terminal output for the exact URL.

Understanding the Project Structure#

Vite’s project structure is minimal and intuitive, avoiding the complexity of tools like CRA. Here’s a breakdown of key files and directories:

my-react-vite-app/
├── node_modules/        # Dependencies (auto-generated)
├── public/              # Static assets (served as-is)
│   ├── favicon.ico      # Default favicon
│   └── robots.txt       # Optional: For search engine crawlers
├── src/                 # Source code
│   ├── assets/          # Images, fonts, etc. (processed by Vite)
│   ├── components/      # React components (e.g., Button.jsx)
│   ├── App.css          # Global styles for App component
│   ├── App.jsx          # Root component
│   ├── index.css        # Global styles
│   └── main.jsx         # Entry point (mounts React to the DOM)
├── .eslintrc.cjs        # ESLint configuration (if TypeScript/ESLint is selected)
├── .gitignore           # Git ignore rules
├── index.html           # HTML entry point (Vite injects scripts here)
├── package.json         # Project metadata and scripts
├── README.md            # Project documentation
└── vite.config.js       # Vite configuration (customize build/dev settings)

Key Files Explained:#

  • index.html: Unlike CRA, Vite uses index.html as the entry point. It references src/main.jsx via a <script type="module"> tag, enabling ESM in the browser.
  • src/main.jsx: The root of your React app. It imports React and ReactDOM, then mounts the App component to the DOM:
    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>,
    )
  • vite.config.js: Vite’s configuration file (we’ll dive into customization later).

Development Workflow: HMR, Scripts, and Live Reload#

Vite’s development workflow is designed for speed. Here’s how to make the most of it:

Hot Module Replacement (HMR)#

Vite’s HMR updates modules in the browser without a full page reload, preserving component state. Try editing src/App.jsx (e.g., change the text inside the <h1> tag)—you’ll see the update instantly in the browser.

npm/Yarn Scripts#

The package.json includes pre-configured scripts for common tasks:

ScriptPurpose
npm run devStarts the development server with HMR (default: http://localhost:5173).
npm run buildBundles the app for production (outputs to dist/ directory).
npm run previewServes the production build locally (useful for testing before deployment).

Example: Adding a Component#

Let’s create a simple Button component to test HMR:

  1. Create src/components/Button.jsx:

    export default function Button({ label }) {
      return (
        <button style={{ padding: '8px 16px', cursor: 'pointer' }}>
          {label}
        </button>
      );
    }
  2. Import and use it in src/App.jsx:

    import Button from './components/Button';
     
    function App() {
      return (
        <div className="App">
          <h1>Hello Vite + React!</h1>
          <Button label="Click Me" />
        </div>
      );
    }
     
    export default App;

Save the files—Vite will update the browser instantly with the new button.

Best Practices for Vite + React Development#

To maximize productivity and maintainability, follow these best practices:

TypeScript adds type safety, catching errors early and improving IDE support. When scaffolding your project, select the TypeScript variant. If you started with JavaScript, migrate later by:

  • Installing TypeScript and type definitions:
    npm install typescript @types/react @types/react-dom --save-dev
  • Renaming .jsx files to .tsx and updating vite.config.js to support TypeScript.

2. Optimize Asset Handling#

Vite automatically processes assets (images, fonts, SVGs) in the src/assets directory. For example:

// Import an image (Vite handles optimization)
import logo from './assets/logo.svg';
 
function App() {
  return <img src={logo} alt="Logo" />;
}

For large assets (e.g., videos), place them in the public/ folder—Vite serves them as static files without processing.

3. Environment Variables#

Vite supports environment variables prefixed with VITE_. Create a .env file in the root directory:

# .env
VITE_API_URL=https://api.example.com

Access variables in your code via import.meta.env:

const apiUrl = import.meta.env.VITE_API_URL;

Note: Variables not prefixed with VITE_ are not exposed to the client for security.

4. Linting and Formatting#

Set up ESLint and Prettier for code quality:

  1. Install dependencies:

    npm install eslint eslint-plugin-react eslint-plugin-react-hooks prettier eslint-config-prettier --save-dev
  2. Create .eslintrc.cjs:

    module.exports = {
      root: true,
      env: { browser: true, es2020: true },
      extends: [
        'eslint:recommended',
        'plugin:react-hooks/recommended',
        'plugin:react/jsx-runtime',
        'prettier' // Disables ESLint rules conflicting with Prettier
      ],
      ignorePatterns: ['dist', '.eslintrc.cjs'],
      parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
      plugins: ['react-refresh'],
      rules: {
        'react-refresh/only-export-components': [
          'warn',
          { allowConstantExport: true },
        ],
      },
    }
  3. Add a script to package.json:

    "scripts": {
      "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0"
    }

5. Code Splitting#

Improve load times by splitting code into smaller chunks. Use React.lazy and Suspense to load components on demand:

import { lazy, Suspense } from 'react';
 
// Lazy-load a component
const HeavyComponent = lazy(() => import('./components/HeavyComponent'));
 
function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <HeavyComponent />
    </Suspense>
  );
}

Advanced Configuration: Customizing Vite#

Vite’s vite.config.js lets you customize the build process, server settings, and plugins. Here are common configurations:

1. Changing the Dev Server Port#

To use a custom port (e.g., 3000) instead of the default 5173:

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
 
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000, // Custom port
    open: true, // Auto-open browser on start
  },
});

2. Proxying API Requests#

If your backend runs on a different port (e.g., http://localhost:4000), proxy API requests to avoid CORS issues:

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

Now, fetch('/api/users') will proxy to http://localhost:4000/users.

3. Adding Plugins#

Vite has a rich ecosystem of plugins. For example, use vite-plugin-svgr to import SVGs as React components:

  1. Install the plugin:

    npm install vite-plugin-svgr --save-dev
  2. Update vite.config.js:

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    import svgr from 'vite-plugin-svgr';
     
    export default defineConfig({
      plugins: [react(), svgr()], // Add svgr plugin
    });
  3. Import SVGs as components:

    import { ReactComponent as Logo } from './assets/logo.svg';
     
    function App() {
      return <Logo />;
    }

Troubleshooting Common Issues#

1. HMR Not Working#

  • Cause: HMR requires components to be pure (no side effects) and avoid state in module scope.
  • Fix: Ensure components are function-based and state is managed with useState/useReducer.

2. Build Failures#

  • Cause: TypeScript errors, missing dependencies, or invalid Vite config.
  • Fix: Run npm run lint to check for errors, ensure all dependencies are installed, and validate vite.config.js.

3. Slow Startup#

  • Cause: Outdated Node.js or too many dependencies.
  • Fix: Update Node.js to the latest LTS version and remove unused dependencies.

4. Environment Variables Not Loading#

  • Cause: Variables not prefixed with VITE_ or .env file in the wrong location.
  • Fix: Rename variables to start with VITE_ and ensure .env is in the project root.

References#

By following this guide, you’ve set up a fast, modern React project with Vite. Enjoy the speed of HMR, optimized builds, and a streamlined development workflow! 🚀