Popular Searches
Popular Course Categories
Popular Courses

Vite React Setup

Vite React Setup

React Project Setup

Vite React Setup – Complete Detailed Notes

Vite React Setup is the process of creating and configuring a React application using Vite, a modern frontend build tool. Vite provides a fast development server, quick updates during development, and optimized production builds. It allows developers to start building React components, pages, and interactive web applications with minimal configuration.

Learn more through JustAcademy React JS Training Course or Register for React JS Course Demo.


1. What Is Vite?

Vite is a frontend development tool used to create, run, and build modern web applications. It supports frameworks such as React, Vue, and others. In a React project, Vite manages the development server, processes application files, and creates optimized production assets.

Key Features of Vite

  • Fast Development Server: Starts the application quickly.
  • Hot Module Replacement (HMR): Updates changed modules in the browser without requiring a full page reload in many cases.
  • React Support: Provides templates and plugins for React development.
  • Production Build: Generates optimized files for deployment.
  • Minimal Configuration: Provides sensible defaults for common projects.
  • Modern JavaScript Support: Works with ES modules, JSX through the React toolchain, and modern frontend features.

2. What Is React?

React is a JavaScript library for building user interfaces. It allows developers to create reusable components and manage dynamic content using props, state, and other React features.

React and Vite have different responsibilities. React builds the user interface, while Vite provides the development and build tooling used by the project.

React Vite
Builds user interfaces. Runs the development server and builds application assets.
Uses components, props, and state. Provides fast development workflows and build commands.
Controls UI rendering. Processes project files and dependencies.
Helps create interactive applications. Helps develop and prepare applications for deployment.

3. Prerequisites for Vite React Setup

Before creating a React application with Vite, install the following tools.

  1. Node.js: Runs JavaScript tools outside the browser and includes npm.
  2. npm: Installs project dependencies and runs development scripts.
  3. Code Editor: Visual Studio Code or another editor can be used to write code.
  4. Web Browser: Chrome, Firefox, Edge, or another modern browser can display the application.
  5. Terminal: Command Prompt, PowerShell, or an integrated editor terminal is used to execute commands.

Check the current Node.js compatibility requirements in the official Vite Getting Started Guide. The required Node.js version can change between Vite releases.

Check Node.js and npm Installation

Open a terminal and run the following commands:

node -v
npm -v

If both commands display version numbers, Node.js and npm are available. If the commands are not recognized, install Node.js and reopen the terminal.

4. Create a React Project Using Vite

The recommended beginner workflow is to create a project using Vite's React template, install dependencies, and start the development server.

Step 1: Open the Terminal

Open Command Prompt, PowerShell, or the terminal inside your code editor. Navigate to the folder where you want to create your project.

Step 2: Create the React Application

Run the following command:

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

Explanation:

  • npm create vite@latest runs the Vite project creation tool.
  • my-react-app is the project folder name. You can replace it with your preferred name.
  • -- passes the following options to the project creation tool.
  • --template react selects the React JavaScript template.

Alternatively, run npm create vite@latest and follow the interactive prompts to select React and JavaScript.

Step 3: Move Into the Project Folder

cd my-react-app

This command changes the current terminal directory to the newly created React project.

Step 4: Install Dependencies

npm install

This command reads the project's package.json file and installs the dependencies required to run the application.

Step 5: Start the Development Server

npm run dev

Vite starts the local development server and displays a local URL in the terminal. Open that URL in your browser to view the React application. The default address is commonly http://localhost:5173/, but the terminal may show a different port if the default is unavailable.

Step 6: Open the Project in a Code Editor

If Visual Studio Code is installed and the code command is configured, run:

code .

This opens the current project folder in Visual Studio Code. You can also open the folder directly from the editor.

5. Complete Vite React Setup Commands

Run these commands one at a time in the terminal:

npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev

Keep the development server running while working on the application. To stop it, focus the terminal and press Ctrl + C.

6. Understanding the Vite React Project Structure

After creating the project, the folder structure will look similar to the following. Some files may differ depending on the template version.

my-react-app/
├── node_modules/
├── public/
├── src/
│   ├── assets/
│   ├── App.css
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
├── .gitignore
├── index.html
├── package.json
├── package-lock.json
├── eslint.config.js
└── vite.config.js

Important Files and Folders

File or Folder Purpose
src/ Contains the main React source code.
src/App.jsx Contains the main application component in the default template.
src/main.jsx Entry point that connects React to the HTML page.
src/App.css Contains styles used by the application component.
src/index.css Contains global styles.
src/assets/ Stores source assets such as images and SVG files.
public/ Stores static assets served directly without being imported into the source module graph.
index.html HTML entry page used by Vite.
package.json Defines project metadata, dependencies, and npm scripts.
package-lock.json Records the resolved npm dependency tree.
vite.config.js Optional Vite configuration file, commonly used to configure plugins and build settings.
node_modules/ Contains installed project dependencies.

7. Understanding the index.html File

In a Vite project, index.html is located in the project root. It provides the HTML document and an element where React can render the application.

A simplified example is:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

Important points:

  • id="root" identifies the HTML element where React mounts the interface.
  • type="module" enables JavaScript module loading.
  • src="/src/main.jsx" points to the React entry file.
  • Vite processes this HTML file as part of the project.

8. Understanding the main.jsx File

The main.jsx file is the entry point for the React application. It imports React, React DOM, the main component, and any global styles required by the project.

Example:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App.jsx';

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

Code Explanation

  • StrictMode helps identify certain potential problems during development.
  • createRoot creates a React root for rendering the interface.
  • document.getElementById('root') selects the root HTML element.
  • App imports the main React component.
  • render() displays the component inside the root element.

9. Understanding the App.jsx File

The App.jsx file usually contains the main React component. You can replace the default starter interface with your own application content.

Example:

function App() {
  return (
    <div>
      <h1>Welcome to React with Vite</h1>
      <p>My first React application is running successfully.</p>
    </div>
  );
}

export default App;

Save the file and return to the browser. Vite's development server should update the page automatically when the changed module can be hot-reloaded.

10. Add CSS to the React Application

You can style React components using ordinary CSS files.

Example: App.css

.app-container {
  max-width: 800px;
  margin: 50px auto;
  padding: 24px;
  text-align: center;
  font-family: Arial, sans-serif;
}

.app-container h1 {
  color: #2563eb;
}

.app-container p {
  color: #444;
  font-size: 18px;
}

Use the CSS in App.jsx

import './App.css';

function App() {
  return (
    <div className="app-container">
      <h1>React + Vite Setup</h1>
      <p>The application is ready for development.</p>
    </div>
  );
}

export default App;

In JSX, use className instead of the HTML class attribute to assign a CSS class to an element.

11. Build a Small Interactive React Application

After setting up Vite, you can test React state and event handling by creating a simple counter.

Counter Example

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

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

  return (
    <div className="app-container">
      <h1>React Counter</h1>
      <p>Current count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

export default App;

How It Works

  • useState(0) creates state with an initial value of zero.
  • count stores the current value.
  • setCount updates the state.
  • onClick handles button clicks.
  • React updates the displayed value when the state changes.

12. Important npm Commands in a Vite React Project

Command Purpose
npm install Installs project dependencies.
npm run dev Starts the development server.
npm run build Creates an optimized production build.
npm run preview Previews the production build locally.
npm install package-name Installs a package for the project.
npm uninstall package-name Removes an installed package.
npm run Lists available npm scripts.

The available commands depend on the scripts defined in package.json.

13. Understanding package.json

The package.json file contains project information, dependencies, and commands used to run development and build tasks.

A simplified example of the scripts section is:

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  }
}

Explanation:

  • dev runs Vite's development server.
  • build generates production-ready files.
  • preview serves the built output locally for testing.

14. What Is Hot Module Replacement (HMR)?

Hot Module Replacement, or HMR, is a development feature that lets Vite update changed modules in the browser without a full page reload in many cases. The React integration also supports fast refresh for compatible component edits.

Example: If you change a heading in App.jsx and save the file, the browser usually reflects the update quickly without manually refreshing the page.

HMR improves the development workflow, but it does not mean that every code change preserves all application state in every situation.

15. Production Build Using Vite

When the application is ready for deployment, create a production build.

npm run build

Vite generates the build output in the dist/ directory by default.

Preview the Production Build

npm run preview

Open the local URL shown in the terminal to check the built application. The preview server is intended for local verification; it is not a replacement for deploying the application to a production hosting service.

Production Build Workflow

Write React components
        ↓
Run the development server
        ↓
Test the application
        ↓
Run npm run build
        ↓
Review the dist folder
        ↓
Deploy the build output

16. Using TypeScript with Vite React

Vite also supports a React TypeScript template. TypeScript adds static type checking to JavaScript development and can help identify certain errors before runtime.

To create a React project with TypeScript, run:

npm create vite@latest my-react-ts-app -- --template react-ts
cd my-react-ts-app
npm install
npm run dev

Use the standard React template if you are learning React with JavaScript first. Choose the TypeScript template when your project or team requires TypeScript.

17. Common Vite React Setup Errors and Solutions

Error or Problem Possible Cause Solution
node is not recognized Node.js is missing or not available in PATH. Install Node.js, reopen the terminal, and run node -v.
npm is not recognized npm is unavailable in the terminal environment. Check the Node.js installation and PATH configuration.
Dependency installation fails Network issues, incompatible versions, or package errors. Read the complete terminal error and verify Node.js and npm compatibility.
Port is already in use Another process is using the default port. Use the alternate URL displayed by Vite or stop the other process.
Blank page in browser JavaScript error, incorrect root element, or import issue. Check the browser console and terminal for errors.
Module not found Incorrect import path or missing dependency. Verify file names, import paths, and package installation.
Changes are not visible File was not saved or the server encountered an error. Save the file, check the terminal, and reload the page if necessary.
Build fails Syntax errors, missing files, or incompatible dependencies. Review the build error and fix the reported issue.

18. Best Practices for Vite React Setup

  • Use a supported Node.js version that meets the requirements of your installed Vite version.
  • Choose clear, meaningful project and component names.
  • Keep reusable components in separate files when the application grows.
  • Separate UI components, styles, and application logic where practical.
  • Install only the packages required by your project.
  • Use version control, such as Git, to track changes.
  • Do not manually edit files inside node_modules/.
  • Check the browser console and terminal when errors occur.
  • Run npm run build before deploying the application.
  • Keep private credentials out of publicly exposed frontend code.

19. Practice Exercise: Create a React Welcome Page

Objective: Create a React application using Vite and display a welcome message, course information, and a button.

Requirements

  1. Create a project named react-welcome-app.
  2. Install the required dependencies.
  3. Start the development server.
  4. Update App.jsx with a welcome heading.
  5. Add CSS styling in App.css.
  6. Create a button that updates a message when clicked.
  7. Run a production build to verify the application.

Sample Code

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

function App() {
  const [message, setMessage] = useState('Welcome to React!');

  return (
    <div className="app-container">
      <h1>My First Vite React Project</h1>
      <p>{message}</p>
      <button onClick={() => setMessage('Your React app is working!')}>
        Click Me
      </button>
    </div>
  );
}

export default App;

20. Frequently Asked Questions (FAQs)

Q1. What is Vite in React?

Vite is a development and build tool used to run and build React applications efficiently.

Q2. Is Vite a replacement for React?

No. React is used to build the user interface, while Vite provides the development server and build tooling.

Q3. How do I create a React application with Vite?

Run npm create vite@latest my-react-app -- --template react, then run cd my-react-app, npm install, and npm run dev.

Q4. Which file starts the React application?

In the standard Vite React template, src/main.jsx is the entry point that renders the main React component.

Q5. What is the purpose of App.jsx?

App.jsx usually contains the main application component, including its UI and component composition.

Q6. What is the default Vite development port?

Vite commonly uses port 5173. If that port is unavailable, it may select another port and display the URL in the terminal.

Q7. What does npm run build do?

It creates an optimized production build, normally in the dist/ folder.

Q8. Can I use TypeScript with Vite React?

Yes. You can select the react-ts template when creating the project.

Q9. Does Vite automatically deploy my application?

No. Vite creates the production build. You must deploy the generated files using a hosting provider or your chosen deployment platform.

Q10. Is Vite suitable for beginners?

Yes. Vite provides a straightforward setup for learning React and building frontend applications, provided the required Node.js version is installed.

21. Quick Revision Checklist

  • Understand the difference between React and Vite.
  • Install and verify Node.js and npm.
  • Create a project using the React template.
  • Run npm install to install dependencies.
  • Run npm run dev to start development.
  • Understand the roles of index.html, main.jsx, and App.jsx.
  • Create components and apply CSS.
  • Use React state and event handlers in a small example.
  • Run npm run build and inspect the dist/ directory.
  • Learn to identify common setup and dependency errors.

22. Conclusion

Vite React Setup provides a simple way to start developing modern React applications. By understanding the setup commands, project structure, entry files, CSS imports, development server, and production build process, developers can create a strong foundation for building interactive websites and frontend projects.

For further learning, visit JustAcademy React JS Training Course or Register for React JS Course Demo.

Additional Learning Resources

Previous Next
whatsapp