Retour aux articles
Friday, December 13, 2024125 vues10

Getting Started with React and Vite: The Complete Guide

Mike Codeur

JavaScript
Vite
Outils

React is one of the most popular JavaScript libraries for building modern, dynamic user interfaces. When paired with Vite, an ultra-fast bundler, you can create performant and maintainable React applications. In this article, we will explore how to get started with React and Vite and the best practices for structuring your application.


Why Choose Vite for Your React Project?

Vite (pronounced "veet", like "vite" in French) is a modern JavaScript development tool. Here’s why it’s ideal for React:

  • Fast Startup: Unlike Webpack or CRA (Create React App), Vite offers near-instant startup time.
  • Hot Module Replacement (HMR): Code changes are instantly applied in the browser without a full reload.
  • Minimal Configuration: No need to manually set up Babel or Webpack—everything is ready to use.
  • Compatible with TypeScript and CSS Modules: Perfect for modern projects.

Prerequisites

Before you start, make sure you have the following tools installed:

  1. Node.js: An LTS version (v18 or higher recommended).
  2. npm or yarn: Included with Node.js, or use pnpm if preferred.

To check if Node.js is installed:

BASH
node -v
npm -v

Creating a Project with Vite

  1. Create a new Vite project with React:

    BASH
    npm create vite@latest project-name -- --template react

    Or with TypeScript:

    BASH
    npm create vite@latest project-name -- --template react-ts
  2. Navigate to the project folder:

    BASH
    cd project-name
  3. Install dependencies:

    BASH
    npm install
  4. Start the development server:

    BASH
    npm run dev

    Vite will start a local server (typically at http://localhost:5173).


Basic Project Structure

Once the project is created, you’ll see a structure like this:

PLAINTEXT
project-name/
├── public/         # Static files
├── src/            # Source code
│   ├── App.jsx     # Main component
│   ├── main.jsx    # Entry point
│   └── assets/     # Images and assets
├── index.html      # Main HTML file
├── package.json    # npm configuration
├── vite.config.js  # Vite configuration

Key Points:

  • App.jsx: Where you build the main interface of your application.
  • main.jsx: Mounts the React app to the DOM using ReactDOM.createRoot.
  • vite.config.js: Configures Vite if needed (e.g., adding aliases).

Adding Additional Features

1. Setting Up CSS Modules

CSS Modules allow you to scope your styles locally.

Create a CSS file in src/:

CSS
/* src/App.module.css */
.container {
  text-align: center;
  color: blue;
}

Then import and use it in your component:

JSX
import styles from './App.module.css';

function App() {
  return (
    <div className={styles.container}>
      <h1>Welcome to React with Vite!</h1>
    </div>
  );
}

export default App;

2. Adding TypeScript

If you chose the JavaScript template but want to switch to TypeScript:

  1. Install dependencies:

    BASH
    npm install --save-dev typescript @types/react @types/react-dom
  2. Add a tsconfig.json file:

    BASH
    npx tsc --init
  3. Rename .jsx files to .tsx.

3. Adding React Router

To handle navigation between pages:

  1. Install React Router:

    BASH
    npm install react-router-dom
  2. Update main.jsx to include the router:

    JSX
    import { BrowserRouter } from 'react-router-dom';
    import App from './App';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <BrowserRouter>
        <App />
      </BrowserRouter>
    );
  3. Set up routes in App.jsx:

    JSX
    import { Routes, Route } from 'react-router-dom';
    import Home from './pages/Home';
    import About from './pages/About';
    
    function App() {
      return (
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      );
    }
    
    export default App;

Tips for Structuring Your Application

  1. Use Reusable Components: Break your UI into small, reusable parts for easier maintenance.
  2. Organize Your Files: Separate your pages, components, and styles into clear folders.
  3. Adopt TypeScript: It makes your code more robust and less error-prone.
  4. Add Tests: Use a framework like Vitest to ensure code reliability.

Conclusion

Getting started with React and Vite is quick and efficient. By following the steps in this guide, you’ll have a performant and modern application ready for deployment. Explore more features of Vite and best practices to create even more powerful applications.

Good luck with your React projects using Vite! 🚀

Abonnes-toi à la NewsLetter

Apprends les meilleures pratiques pour devenir un développeur web moderne (JavaScript / React / Next).

Gagner sa vie grâce au code
Devenir développeur Freelance
+35 000 développeurs déjà inscrits.

Accès instantané. Aucune carte de crédit requise.

Rejoins +35 000 développeurs déjà inscrits.