How to Set Up a React Project with Vite: Setup and Best Practices

In modern front-end development, Vite has quickly become a go-to tool for building fast and optimized projects. It’s lightweight, highly efficient, and supports a wide range of frameworks, including React. In this article, we’ll walk through how to set up a React project with Vite, and share some useful configurations like how to set the base URL to streamline development.

Why Choose Vite?

Vite is a next-generation build tool that provides several benefits:

  • Fast Startup: Vite’s dev server starts in seconds, even for large projects.
  • Instant Hot Module Replacement (HMR): Changes to your code reflect in the browser in milliseconds, making for a smooth development experience.
  • Efficient Build: Vite uses ESBuild for transpiling and bundling, which makes the build process much faster than traditional bundlers.
  • Out-of-the-box Configuration: Vite offers a lot of sensible defaults, so you can get started with minimal configuration.

Now, let’s dive into how to set up a React project with Vite and walk through some common configurations.

Step 1: Install Vite and Create a React Project

First, let’s install Vite and create a new React project. Open your terminal and run the following command:

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

This command will create a new React project called my-react-app. Vite will automatically set up the necessary dependencies for React.

Next, navigate into the project directory and install the dependencies:

cd my-react-app
npm install

Your React project is now set up and ready for development!

Step 2: Set the Base URL

Many projects require setting a base URL, especially when deploying your app to services like github pages or gitlab pages. If you don’t set it properly, your static assets might not load correctly.

In Vite, setting the base URL is very simple. Just modify the vite.config.js file.

  1. Open the vite.config.js file.
  2. Find the base configuration and update it. For example, if your project is deployed at https://example.com/my-react-app/, you should set the base to /my-react-app/:
import { defineConfig } from 'vite'

export default defineConfig({
  base: '/my-react-app/',  // Set the base URL
  // other configurations...
})

This will ensure that Vite appends /my-react-app/ to all static asset URLs when building your project.

If your project is deployed at the root of your domain, simply set base: '/'.

Step 3: Install and Configure React Router

If your React application will have multiple pages or views, you’ll likely need React Router for handling routing between different components. Since React Router is not bundled with Vite by default, you’ll need to install it separately.

3.1 Install React Router

To install React Router, run the following command in your project directory:

npm install react-router-dom

This will install the necessary packages for React Router DOM to manage client-side routing.

3.2 Configure React Router

Once React Router is installed, you can start setting it up in your React app. In your src/App.js (or wherever you manage your app’s routes), you’ll need to import the necessary components from react-router-dom and configure your routes.

Here’s an example of how to set it up, including the basename configuration for deployments to subdirectories (as mentioned earlier):

import React from 'react'
import { BrowserRouter, Route, Routes } from 'react-router-dom'

function App() {
  return (
    <BrowserRouter basename="/my-react-app">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  )
}

export default App

Explanation:

  • BrowserRouter: This component is responsible for managing the history of your browser’s URL and syncing it with your application.
  • basename: This property ensures that all your routes are prefixed with the basename (e.g., /my-react-app). This is especially important when deploying your app to a subdirectory (such as https://example.com/my-react-app/).
  • Routes: This component wraps your route definitions, and you can define individual routes using the Route component.
  • element: The element prop specifies the component that should be rendered for a given route.

With this setup, your React app will be able to navigate between pages, and the routes will work even when the app is deployed in a subdirectory.

Step 4: Set Up Environment Variables

Vite supports environment variables, which are useful for configuring API endpoints or other build settings that differ between environments (e.g., development, production).

  1. Create an .env file in the root of your project:
VITE_API_URL=https://api.example.com
  1. In your React components, you can use these environment variables:
const apiUrl = import.meta.env.VITE_API_URL;
console.log(apiUrl);  // https://api.example.com

Vite automatically reads and injects variables from .env files, but only variables prefixed with VITE_ are exposed to the client-side code.

Step 5: Optimize and Debug

As your project grows, you might encounter performance or debugging needs. Vite offers several features to help optimize your development experience:

  • Proxy Setup: If you’re working with APIs on a different domain, you might run into CORS issues. You can set up a proxy in the vite.config.js file:
export default defineConfig({
  server: {
    proxy: {
      '/api': 'http://localhost:5000'
    }
  }
})

This ensures that requests to /api are proxied to http://localhost:5000, avoiding cross-origin issues.

  • Hot Module Replacement (HMR): Vite’s HMR feature ensures that your application updates instantly when code changes, giving you a smooth and fast development workflow.

Conclusion

By following these steps, you’ve learned how to quickly set up a React project with Vite and configure essential settings like the base URL, React Router’s basename, and environment variables. Vite’s powerful features and fast development server make React development faster and more efficient.

If you run into any issues or have further questions, feel free to leave a comment or refer to the Vite Documentation for more advanced configurations.

This article was assisted by Chatgpt.

This article was updated on November 17, 2024

sk5s

Comments