Maison  >  Article  >  interface Web  >  Tutoriel : Comment créer une application React avec Vite

Tutoriel : Comment créer une application React avec Vite

DDD
DDDoriginal
2024-10-11 10:29:01335parcourir

1. Présentation

Dans le monde du frontend JavaScript, de nouveaux outils émergent constamment pour créer et optimiser les projets. React, une bibliothèque JavaScript populaire pour la création d'interfaces utilisateur, est traditionnellement associée à Create-React-App (CRA) pour simplifier la configuration et le développement. Cependant, un outil plus récent appelé Vite gagne rapidement du terrain en raison de sa rapidité et de son efficacité, offrant une alternative moderne à l'ARC.

Dans cet article de blog, nous commencerons par présenter les fonctionnalités spécifiques qui font de Vite un excellent choix pour les développeurs React, puis nous examinerons de plus près Create-React-App. Ensuite, nous comparerons les deux outils pour vous aider à décider quand utiliser chacun d'eux et quand passer de CRA à Vite.

Que vous démarriez un nouveau projet React ou envisagiez de migrer un projet existant, nous vous guiderons tout au long du processus, vous aidant à choisir le meilleur outil pour vos besoins. De plus, nous explorerons les techniques avancées de configuration et d'optimisation pour ceux qui souhaitent tirer le meilleur parti de leur configuration Vite et React.

À la fin de cet article, vous aurez des réponses aux questions clés suivantes :

  1. Quelles sont les fonctionnalités uniques de Vite qui en font un excellent choix pour le développement de React ?

  2. Comment Create-React-App se compare-t-il à Vite en termes de performances, de configuration et de flexibilité ?

  3. Quand devriez-vous vous en tenir à Create-React-App et quand est-il préférable de passer à Vite ?

  4. Quelles sont les étapes à suivre pour monter un nouveau projet React avec Vite ?

  5. Comment migrer un projet Create-React-App existant vers Vite ?

  6. Quelles techniques avancées de configuration et d'optimisation pouvez-vous appliquer pour tirer le meilleur parti de votre configuration Vite et React ?

2. Qu'est-ce que Vite ?

Tutorial: How to Create a React App with Vite

Vite est un outil de construction conçu pour rendre le développement Web plus rapide et plus efficace. Le nom « Vite » vient du mot français signifiant « rapide ». Créé par Evan You, le même développeur derrière Vue.js, Vite a été conçu pour répondre aux limitations de performances des bundles traditionnels comme Webpack.

Il prend en charge les frameworks populaires tels que React, Vue et Svelte. Sa flexibilité le rend compatible avec un large éventail de technologies front-end, lui permettant ainsi de s'adapter aux différents besoins de développement. Il exploite les modules ECMAScript natifs et les capacités du navigateur moderne pour fournir un environnement de développement rapide.

Peu importe si vous créez une application React simple ou une application Web complexe, Vite offre une expérience simplifiée qui peut vous faire gagner du temps.

2.1 Pourquoi Vite a-t-il été créé ?

Les outils de build traditionnels comme Webpack existent depuis des années et ont bien servi la communauté des développeurs. Cependant, à mesure que les applications Web gagnaient en complexité, le temps nécessaire pour démarrer un serveur de développement et voir les modifications reflétées dans le navigateur augmentait également.

L'image suivante décrit l'approche de regroupement traditionnelle. Le processus commence par un point d’entrée qui se connecte aux différentes routes et modules de l’application. Tous ces composants sont regroupés avant que le serveur soit prêt à être utilisé. Ce regroupement initial prend du temps, d'autant plus que l'application se développe, ce qui entraîne des temps de démarrage plus longs pour le serveur de développement.

Tutorial: How to Create a React App with Vite

Vite adopte une approche différente pour créer et servir votre application pendant le développement. Au lieu de tout regrouper à l'avance, le serveur est prêt presque instantanément et le navigateur ne demande que les modules spécifiques dont il a besoin lorsqu'ils sont nécessaires. Ceci est rendu possible grâce à la prise en charge des modules ES natifs (ESM), qui permettent des importations dynamiques, permettant le fractionnement du code et réduisant la quantité de code à traiter à un moment donné. En ne servant que ce qui est nécessaire, Vite assure une boucle de rétroaction beaucoup plus rapide, permettant aux développeurs de travailler plus efficacement.

Tutorial: How to Create a React App with Vite

2.2 Principales caractéristiques de Vite

Voici les fonctionnalités principales de Vite :

  • Démarrage instantané du serveur :
    Avec les outils traditionnels, le démarrage du serveur de développement peut prendre un certain temps, notamment pour les grands projets. Vite, cependant, démarre presque instantanément. Pour ce faire, il transforme uniquement le code sur lequel vous travaillez actuellement, et non l'ensemble du projet. Cela rend votre expérience de développement beaucoup plus fluide et plus réactive.

  • Remplacement ultra-rapide du module chaud (HMR) :
    Le remplacement à chaud du module (HMR) vous permet de voir les résultats des modifications de votre code en temps réel, sans avoir besoin d'actualiser le navigateur. Le HMR de Vite est incroyablement rapide car il met à jour uniquement les modules spécifiques qui ont été modifiés, et non l'ensemble de l'application. Cette boucle de rétroaction instantanée permet un processus de développement beaucoup plus efficace.

  • Prise en charge des modules ES natifs :
    Vite exploite la prise en charge native du module ES intégrée aux navigateurs modernes. Au lieu de regrouper l'intégralité de votre base de code dans quelques fichiers volumineux (comme avec les outils traditionnels), Vite sert chaque module comme un fichier distinct. Cela réduit le besoin de transformations complexes et accélère à la fois le chargement initial et les mises à jour ultérieures.

  • Processus de construction optimisé à l'aide du Rollup :
    Vite est également puissant en production. Lorsque vous êtes prêt à déployer, Vite regroupe efficacement votre code à l'aide de Rollup, un regroupeur de modules moderne. Cela signifie que vous obtenez le meilleur des deux mondes : un développement rapide et des versions de production optimisées.

  • Configuration flexible dans vite.config.js :
    Vite est hautement personnalisable. Avec un fichier de configuration simple (vite.config.js), vous pouvez facilement modifier les paramètres pour répondre aux besoins de votre projet. Que vous ayez besoin de configurer des variables d'environnement, de configurer des alias de chemin ou d'ajouter des plugins, Vite simplifie les choses.

  • Prise en charge de TypeScript natif :
    React et Vite prennent en charge nativement TypeScript, ce qui facilite l'intégration de la saisie statique dans votre code. L'utilisation de TypeScript permet de détecter les erreurs plus tôt dans le processus de développement et améliore la maintenabilité du code.

3. Qu'est-ce que Create-React-App ?

Create-React-App (CRA) est un outil populaire développé par Facebook qui simplifie le processus de mise en place d'un nouveau projet React. Il permet aux développeurs de commencer rapidement à créer des applications React sans avoir besoin de configurer manuellement un environnement de développement.

3.1 Pourquoi Create-React-App a-t-il été créé ?

Avant CRA, la mise en place d'un projet React nécessitait de configurer une variété d'outils, ce qui pouvait être une tâche ardue, en particulier pour ceux qui découvrent React. Pour relever ce défi, CRA a été introduit en 2016 en tant que solution offrant une configuration sans configuration. Cet outil a permis aux développeurs de se lancer directement dans l'écriture de code React sans se soucier de la complexité des outils de construction et des configurations.

CRA est rapidement devenu l'outil standard des développeurs React car il rationalise la configuration des projets et apporte de la cohérence aux environnements de développement, facilitant ainsi la collaboration efficace des équipes.

3.2 Principales fonctionnalités de Create-React-App

Voici les principales fonctionnalités de CRA :

  • Création d'un arbre de dépendances avec Webpack :
    L'ARC utilise Webpack pour analyser le fichier index.js de votre projet, qui sert de point d'entrée à votre application. Webpack crée ensuite une arborescence de dépendances en reliant entre eux tous les modules dont votre projet a besoin. Ce processus automatisé garantit que votre candidature dispose de toutes les ressources nécessaires regroupées.

  • Transpilation de code avec Babel :
    Une fois l'arborescence des dépendances créée, CRA utilise Babel pour transpiler votre JavaScript moderne dans une version compatible avec un plus large éventail de navigateurs. Cette étape garantit que votre application peut fonctionner correctement dans différents environnements, qu'ils prennent ou non en charge les dernières fonctionnalités JavaScript.

  • Regroupement et diffusion de codes :
    Après transpilation, Webpack regroupe le code de votre application dans quelques fichiers compressés. Ces bundles sont ensuite servis via un serveur Web, rendant votre application accessible via un serveur de développement local.

  • Aucune configuration requise :
    L'un des plus grands avantages de CRA est qu'il fournit une configuration React entièrement fonctionnelle. Lorsque vous créez un nouveau projet avec CRA, il configure automatiquement tout ce dont vous avez besoin, comme Webpack pour le regroupement, Babel pour la transpilation de JavaScript moderne et ESLint pour le peluchage. Cela signifie que vous pouvez commencer à coder immédiatement sans passer du temps à configurer votre environnement.

4. Pourquoi envisager de passer de Create-React-App à Vite ?

Dans cette section, nous comparerons Vite et CRA dans plusieurs domaines clés tels que la configuration, les performances, la prise en charge et les fonctionnalités pour vous aider à déterminer quand il pourrait être judicieux de passer de CRA à Vite.

Comparaison 4.1 : Vite et Create-React-App

Create-React-App Vite
Configuration Zero Configuration: CRA is known for its zero-configuration setup. You can create a new React project with a single command, and everything is ready to go, including Webpack, Babel, and ESLint. Simple and Flexible Configuration: Vite offers a straightforward setup process, but with greater flexibility. Vite's configuration is minimal and easy to customize through a vite.config.js file. You can add plugins, configure build options, and set up environment variables with ease. This makes Vite a better choice for projects where you anticipate needing custom configurations.
Performance Traditional Bundling: CRA relies on Webpack for bundling your application. While Webpack is powerful, it can be slow, especially as your project grows. The initial server start-up time and the time it takes to reflect changes in the browser can increase significantly, leading to longer development cycles. (Traditional Bundling Process) Instant Development with ES Modules: Vite’s approach to development is centered around speed. By using native ES modules, Vite eliminates the need for bundling during development, resulting in nearly instant server start times. Changes to your code are reflected immediately in the browser, thanks to Vite’s lightning-fast HMR. For larger projects, the performance difference is especially noticeable. (Vite's Process)
Support and Ecosystem Mature Ecosystem: CRA has been around for several years and has a large, active community. This means there is a wealth of tutorials, plugins, and third-party tools available. Additionally, because CRA is backed by Facebook, it has strong support and regular updates. For developers who prefer stability and extensive community resources, CRA remains a solid choice. Growing Ecosystem: While Vite is newer, it has quickly gained traction in the developer community. Its plugin ecosystem is expanding rapidly, with support for various frameworks and tools. Vite is also highly compatible with modern JavaScript features and has a growing number of contributors.
Features - All-in-one solution
- Built-in testing tools like Jest and React Testing Library
- Built-in service workers for Progressive Web Apps (PWAs)
- Environment variable management
- Modular and extensible
- Support for JSX and TypeScript
- Plugin-Based Architecture
- Fast Development Server
- Environment Variable Management

4.2 Wann man die einzelnen Tools nutzt und wann ein Wechsel in Betracht gezogen werden sollte

  1. Wann man die Create-React-App verwenden sollte:
  • Für Anfänger:
    Wenn Sie neu bei React oder der Front-End-Entwicklung sind, ist CRA ein guter Ausgangspunkt. Wenn Sie beispielsweise eine einfache Portfolio-Website oder einen persönlichen Blog erstellen, können Sie sich dank des Null-Konfigurations-Ansatzes auf das Erlernen von React konzentrieren, ohne sich um die zugrunde liegende Einrichtung kümmern zu müssen.

  • Für kleine bis mittlere Projekte:
    CRA eignet sich gut für kleinere Projekte, bei denen die einfache Einrichtung und Verwendung wichtiger ist als die Feinabstimmung von Leistung oder Konfiguration. CRA eignet sich beispielsweise perfekt für Projekte wie das interne Dashboard eines Unternehmens oder eine kleine E-Commerce-Site.

  • Für Stabilität:
    Wenn Sie ein langfristiges Projekt entwickeln, das ein stabiles und weithin unterstütztes Tool benötigt, wie ein Schulverwaltungssystem oder die Website einer Organisation, ist CRA aufgrund seiner großen Community und robusten Dokumentation eine zuverlässige Wahl. Sie müssen sich keine Sorgen über häufige Breaking Changes machen und können sich auf die Unterstützung der Community verlassen.

  1. Wann sollte Vite verwendet werden:
  • Für Geschwindigkeit und Leistung:
    Wenn Sie an einer umfangreichen Anwendung arbeiten, beispielsweise einer Social-Media-Plattform oder einem komplexen Datenvisualisierungs-Dashboard, ist die Geschwindigkeit von Vite von entscheidender Bedeutung. Wenn Ihre App beispielsweise zahlreiche Seiten oder Komponenten enthält, können die schnellen Build-Zeiten und der effiziente Hot Module Replacement (HMR) von Vite die Zeit reduzieren, die Sie während der Entwicklung mit dem Warten auf Updates verbringen.

  • Für moderne Entwicklungspraktiken:
    Wenn Ihr Projekt auf modernen JavaScript-Praktiken wie der Verwendung von ES-Modulen basiert oder wenn Sie mit hochmodernen Bibliotheken wie Svelte integrieren oder TypeScript verwenden, bietet Vite sofort einsatzbereite Unterstützung, die Ihren Arbeitsablauf optimieren kann. Ein Beispiel wäre die Entwicklung einer modernen SaaS-Plattform, bei der Sie über die neuesten Webstandards und -funktionen auf dem Laufenden bleiben müssen.

  • Für Flexibilität:
    Wenn Sie eine hochgradig individuelle Anwendung erstellen, beispielsweise ein CMS, das auf eine bestimmte Branche zugeschnitten ist, können Sie mithilfe des Plugin-Systems und der modularen Architektur von Vite problemlos Tools wie Tailwind CSS, Preact oder andere integrieren, die Ihren Anforderungen entsprechen. Diese Flexibilität ist besonders nützlich für Anwendungen, bei denen die Standardkonfiguration erhebliche Anpassungen erfordert, um spezifische Anforderungen zu erfüllen.

  1. Wann sollte ein Wechsel von CRA zu Vite in Betracht gezogen werden:
  • Ihr Projekt und Ihre Benutzerbasis beginnen deutlich zu wachsen:
    Stellen Sie sich vor, Sie beginnen mit CRA, um ein kleines Projektmanagement-Tool zu entwickeln. Wenn weitere Funktionen hinzugefügt werden und die Benutzerbasis wächst, stellen Sie möglicherweise fest, dass sich die Erstellungszeiten und die Startzeiten des Entwicklungsservers erheblich verlängern. An diesem Punkt kann Ihnen der Wechsel zu Vite dabei helfen, einen schnellen Entwicklungszyklus aufrechtzuerhalten, sodass Sie neue Funktionen effizienter hinzufügen können.

  • Sie suchen eine hervorragende Entwicklererfahrung:
    Angenommen, Sie arbeiten an einer Echtzeit-App für die Zusammenarbeit, bei der schnelles Feedback während der Entwicklung von entscheidender Bedeutung ist. CRA wird möglicherweise langsamer, wenn die Komplexität Ihrer App zunimmt. Durch den Wechsel zu Vite können Sie von den schnelleren Serverstarts und HMR profitieren, was zu einem reaktionsschnelleren Entwicklungsprozess führt.

  • Um mit modernen Tools immer einen Schritt voraus zu sein:
    Wenn Sie eine Tutorial-Site betreiben, die die neuesten Webentwicklungspraktiken präsentieren muss, könnte der Wechsel von CRA zu Vite von Vorteil sein. Mit diesem Wechsel können Sie moderne Tools und Methoden demonstrieren und so dazu beitragen, dass Ihre Inhalte für ein zukunftsorientiertes Publikum relevant und informativ bleiben.

5. Erste Schritte mit Vite und React

In diesem Abschnitt führen wir Sie durch zwei verschiedene Ansätze zur Verwendung von Vite mit React. Egal, ob Sie ein neues Projekt starten oder ein bestehendes Create-React-App (CRA)-Projekt auf Vite aktualisieren möchten, wir sind für Sie da.

5.1 Voraussetzungen

In diesem Tutorial wird davon ausgegangen, dass Sie über grundlegende Kenntnisse von React und JavaScript verfügen. Stellen Sie zunächst sicher, dass Node.js und NPM auf Ihrem Computer installiert sind.

5.2 Richten Sie ein React-Projekt mit Vite ein

Das Starten eines neuen React-Projekts mit Vite ist schnell und unkompliziert. Wenn Sie den vollständigen Code sehen möchten, schauen Sie sich unser React Application with Vite-Repository auf GitHub an.

So können Sie loslegen:

1. Erstellen Sie ein neues Vite-Projekt

Öffnen Sie zunächst Ihr Terminal und führen Sie den folgenden Befehl aus, um ein neues Vite-Projekt mit React als Vorlage zu erstellen:

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

2. Navigieren Sie zu Ihrem Projektverzeichnis

Nachdem das Projekt erstellt wurde, wechseln Sie in das Projektverzeichnis:

cd my-react-vite-app

3. Select a Variant

TypeScript

4. Install Dependencies

Next, install the required dependencies by running:

npm install

5. Start the Development Server

Once the installation is complete, start the development server:

npm run dev

Your project should now be running locally, and you can see it in action by opening your browser and navigating to http://localhost:5173/
Tutorial: How to Create a React App with Vite
And that’s it! You’ve successfully set up a new React project using Vite.

5.3 Migrate an existing CRA Project to Vite

We will guide you through migrating an existing Create-React-App (CRA) project to Vite. If you want to see the complete code, check out our Migrate CRA to Vite repository on GitHub.To make the migration process clear and accessible, we'll start by creating a new CRA project using npx, and then proceed with the migration to Vite.

Npx is a command-line tool that comes with npm (version 5.2.0 and above). While npm is used to install packages globally or locally, npx allows you to execute packages without installing them permanently. For example, when you run npx create-react-app my-app, npx temporarily downloads and executes the create-react-app package to generate a new React project.

1. Create a New React App with Create-React-App (CRA)

If you don't already have an existing CRA project, you can create one using npx. This will give us a starting point for the migration process.

Open your terminal and run the following command to create a new React app using CRA:

npx create-react-app my-cra-app

This command will set up a new React project named my-cra-app with all the default configurations provided by CRA.

2. Navigate to the project directory once the setup is complete:

cd my-cra-app

3. Run the development server to ensure everything is set up correctly:

npm start

This command will start the CRA development server, and you can see your new React app running at http://localhost:3000.
Tutorial: How to Create a React App with Vite
At this point, you have a working CRA project that we will now migrate to Vite.

4. Install Vite

Stop the CRA development server if it's running, and then install Vite as a dependency:

npm install vite

5. Install the Vite React plugin

It will handle React-specific features:

npm install @vitejs/plugin-react

6. Create index.html

Create the index.html file in the root of your project.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>React Vite Migration</title>
  </head>
  <body>
    <p>Hello Vite!</p>
  </body>
</html>

7. Create vite.config.js

In the root directory of your project, create a file named vite.config.js and add the following configuration:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
  plugins: [react()],
});

This file configures Vite to work with React, enabling JSX and other React-specific features.

8. Update package.json Scripts

Open your package.json file and replace the existing CRA scripts with Vite equivalents:

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

The dev script starts the Vite development server, build creates a production build and serve allows you to preview the build locally.

9. Start the Development Server

npm run dev

Your project should now be running locally, and you can see it in action by opening your browser and navigating to http://localhost:5174

Tutorial: How to Create a React App with Vite

Once you’ve set up your React project with Vite, it’s time to add some advanced configuration and optimization techniques. This section will help you customize your Vite setup to fit your project’s specific needs and ensure your application is optimized for production.

6.Advanced Configuration and Optimization

The vite.config.js file is where you can customize your Vite setup to suit the requirements of your project. Let’s go through the key areas you might want to adjust and how to do it.

6.1 Adding and Configuring Plugins

Vite has a powerful plugin system that allows you to extend its functionality. For example, if you need to add support for additional features like TypeScript, you can include relevant plugins in the plugins array.

Here’s an example:

import react from "@vitejs/plugin-react";

import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [react(), tsconfigPaths()],
});

6.2 Adding Path Aliases

Path Aliases reduces the need for long relative paths and makes your code easier to navigate.

First, configure path aliases in Vite by modifying the vite.config.js file:

import path from "path";

resolve: {
    alias: {
        "@components": path.resolve(__dirname, "src/components"),
        "@assets": path.resolve(__dirname, "src/assets"),
        "@utils": path.resolve(__dirname, "src/utils"),
    },
}

These aliases allow you to import modules using cleaner paths, such as:

import Header from '@components/Header';

6.3 Customizing the Development Server

You can customize the development server to fit your needs. For example, you might want to change the default port.

Here’s the relevant configuration:

server: {

    port: 3000, // Default port is 5173, but you can change it to 3000 or any other port

    open: true, // Open the browser automatically

}

6.4 Configuring the Build Process

The build section in vite.config.js allows you to customize how your project is bundled for production. You can specify the output directory, enable source maps for debugging, and more.

build: {
    outDir: 'dist', // Customize the output directory
    sourcemap: true, // Generate source maps for easier debugging
    minify: 'esbuild', // Use esbuild for minification (default is Terser)
},

6.5 Optimizing for Production

When preparing your project for production, there are several strategies you can use to optimize your build output:

  • Lazy Loading Components
    For large React applications, consider using React’s lazy() and Suspense to load components only when they’re needed. This reduces the initial load time and improves the perceived performance of your application.

  • Splitting Large Components:
    Break down large components into smaller, self-contained components that can be lazy loaded. This minimizes the amount of JavaScript that needs to be loaded initially.

  • Analyzing the Bundle Size
    Use tools like rollup-plugin-visualizer to analyze your bundle size and see which parts of your application are taking up the most space. This can help you identify optimization opportunities.

7. Conclusion

Vite and Create-React-App (CRA) both serve as powerful tools for React development, each with its unique strengths. CRA is an excellent starting point for beginners and small to medium-sized projects, offering a zero-configuration setup that lets you dive straight into coding. However, as your project grows, CRA's performance can start to lag, and its rigid configuration may feel limiting. This is where Vite shines.

Vite offers lightning-fast development with instant server start and quick Hot Module Replacement (HMR), making it ideal for larger projects and developers seeking more control. With modern tooling, simplified yet flexible configuration, and optimized production builds, Vite provides a streamlined and future-proof development experience. Whether you’re starting a new project or considering a switch, Vite offers the speed and flexibility to enhance your workflow, making it a compelling choice for modern React development.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn