Heim > Web-Frontend > js-Tutorial > Hauptteil

Ein Anfängerleitfaden zur Verwendung von Vite mit React

王林
Freigeben: 2024-09-05 22:33:33
Original
880 Leute haben es durchsucht

A beginners guide to using Vite with React

Einführung

Wenn Sie ein neues React-Projekt starten, kann die Auswahl der richtigen Tools einen großen Einfluss auf Ihren Workflow haben. Während Tools wie Webpack seit Jahren weit verbreitet sind, bieten neuere Optionen wie Vite schnellere und effizientere Alternativen.

Vite wurde von Evan You (dem Erfinder von Vue.js) entwickelt und ist darauf ausgelegt, eine blitzschnelle Entwicklungsumgebung bereitzustellen. Dies geschieht durch die Bereitstellung von Dateien über native ES-Module und die Verwendung eines optimierten Entwicklungsservers. Dies führt zu schnelleren Serverstartzeiten und einer reaktionsschnelleren Entwicklung.

React, eine der beliebtesten Bibliotheken zum Erstellen von Benutzeroberflächen, funktioniert nahtlos mit Vite. Seine komponentenbasierte Architektur eignet sich ideal für die Entwicklung dynamischer Single-Page-Anwendungen (SPAs). Darum ist Vite eine gute Wahl für React-Projekte:

  • Sofortiger Serverstart: Im Gegensatz zu herkömmlichen Bundlern startet der Entwicklungsserver von Vite fast sofort, indem er Dateien als native ES-Module bereitstellt und so eine Bündelung während der Entwicklung vermeidet.

  • Fast Hot Module Replacement (HMR): Vites HMR ist unglaublich schnell, sodass Sie Änderungen in Ihren React-Komponenten fast sofort erkennen können, was die Entwicklung beschleunigt.

  • Optimierte Produktions-Builds: Für die Produktion verwendet Vite Rollup, um Ihre Bundles zu optimieren. Es umfasst Funktionen wie die automatische Codeaufteilung, die die Ladezeit Ihrer App verbessert.

  • Moderne Entwicklungsunterstützung: Vite funktioniert gut mit modernen JavaScript-Tools wie TypeScript, JSX und CSS-Präprozessoren wie Sass und bietet sofort ein hochmodernes Entwicklungserlebnis.

In diesem Blog führen wir Sie durch die Einrichtung eines React-Projekts mit Vite, erkunden die Struktur des Projekts und zeigen Ihnen, wie Sie mit Assets arbeiten und Ihre App bereitstellen. Am Ende werden Sie sehen, wie Vite Ihre React-Entwicklungserfahrung verbessern kann.

Was ist Vite?

Vite ist ein modernes Build-Tool, das auf Geschwindigkeit und Effizienz ausgelegt ist, insbesondere bei der Arbeit mit JavaScript-Frameworks wie React. Vite wurde von Evan You, dem Erfinder von Vue.js, entwickelt und zeichnet sich durch seine Fähigkeit aus, ein schnelles und optimiertes Entwicklungserlebnis zu bieten.

Hauptmerkmale von Vite

  1. Sofortiger Serverstart: Vite stellt Dateien über native ES-Module bereit, sodass der Entwicklungsserver selbst bei großen Projekten nahezu sofort gestartet werden kann.

  2. Fast Hot Module Replacement (HMR): Vites HMR ist extrem schnell und ermöglicht nahezu sofortige Aktualisierungen Ihrer React-Komponenten während der Entwicklung.

  3. Optimierte Builds: Vite verwendet Rollup für Produktions-Builds und gewährleistet so eine effiziente Bündelung mit Funktionen wie Code-Splitting und Tree-Shaking.

  4. Moderne JavaScript-Unterstützung: Vite bietet integrierte Unterstützung für die neuesten JavaScript-Funktionen, einschließlich TypeScript, JSX und CSS-Präprozessoren wie Sass.

Vite vs. Webpack

Während Webpack seit Jahren eine beliebte Wahl ist, erfordert es oft komplexe Konfigurationen und kann aufgrund seines Bündelungsprozesses während der Entwicklung langsamer sein. Im Gegensatz dazu vereinfacht Vite den Einrichtungsprozess und überspringt die Bündelung während der Entwicklung, was zu schnelleren Serverstartzeiten und HMR führt. Die Produktions-Builds von Vite sind ebenfalls stark optimiert, ähnlich wie die von Webpack, jedoch mit einer einfacheren Konfiguration.

Warum Vite mit React verwenden?

  1. Geschwindigkeit: Vites schneller Serverstart und HMR erleichtern die Entwicklung von React-Anwendungen, ohne auf lange Bündelungsprozesse warten zu müssen.

  2. Einfachheit: Dank der benutzerfreundlichen Einrichtung von Vite können Sie sich auf die Erstellung Ihrer React-Komponenten konzentrieren, anstatt Build-Tools zu konfigurieren.

  3. Effizienz: Vite sorgt dafür, dass Ihre React-App nicht nur schnell entwickelt, sondern auch mit minimalem Aufwand für die Produktion optimiert wird.

Vite bietet eine modernere und effizientere Alternative zu herkömmlichen Bundlern wie Webpack und eignet sich daher hervorragend für React-Projekte, bei denen Geschwindigkeit und Einfachheit im Vordergrund stehen.

Einrichten der Entwicklungsumgebung

Bevor Sie mit React in Vite eintauchen, müssen Sie sicherstellen, dass Node.js und npm auf Ihrem System installiert sind. Wenn Sie sie noch nicht installiert haben, führen Sie die folgenden Schritte aus, um zu beginnen.

Node.js und npm installieren

Um Node.js und npm zu installieren, besuchen Sie die offizielle Website von Node.js und laden Sie die neueste stabile Version herunter. Nach der Installation können Sie die Installation überprüfen, indem Sie die folgenden Befehle in Ihrem Terminal ausführen:

node -v
npm -v
Nach dem Login kopieren

Arahan ini harus memaparkan versi Node.js dan npm yang dipasang, mengesahkan bahawa ia telah disediakan dengan betul.

Memulakan Projek Vite Baharu

Dengan Node.js dan npm sedia, anda kini boleh membuat projek React baharu menggunakan Vite. Vite menyediakan arahan mudah untuk menyediakan projek baharu dengan cepat. Buka terminal anda dan jalankan arahan berikut:

npm create vite@latest my-react-app --template react
cd my-react-app
npm install
Nach dem Login kopieren
  • npm create vite@latest my-react-app --template react: Perintah ini memulakan projek Vite baharu dengan templat React. Gantikan aplikasi-my-react dengan nama projek yang anda inginkan.
  • cd my-react-app: Navigasi ke dalam direktori projek anda yang baru dibuat.
  • pemasangan npm: Pasang kebergantungan yang diperlukan untuk projek React anda.

Menjalankan Pelayan Pembangunan

Setelah projek anda disediakan dan kebergantungan dipasang, anda boleh memulakan pelayan pembangunan. Pelayan Vite adalah pantas, dan anda akan melihat seberapa cepat ia bermula:

npm run  dev
Nach dem Login kopieren

Menjalankan arahan ini akan memulakan pelayan pembangunan Vite dan membuka aplikasi React baharu anda dalam pelayar web lalai anda. Aplikasi akan dimuat semula secara automatik semasa anda membuat perubahan pada kod, terima kasih kepada ciri Penggantian Modul Panas (HMR) Vite yang pantas.

Menjalankan arahan ini akan memulakan pelayan pembangunan Vite dan membuka aplikasi React baharu anda dalam pelayar web lalai anda. Aplikasi akan dimuat semula secara automatik semasa anda membuat perubahan pada kod, terima kasih kepada ciri Penggantian Modul Panas (HMR) Vite yang pantas.

Memahami Struktur Projek

Vite menyediakan struktur projek yang ringkas dan teratur. Berikut ialah ikhtisar ringkas fail dan folder utama:

  • index.html: Titik masuk permohonan anda. Vite menyuntik skrip anda ke dalam fail ini.
  • src/main.jsx: Fail JavaScript utama tempat aplikasi React anda bermula. Ia biasanya menjadikan komponen akar (App.jsx) ke dalam DOM.
  • src/App.jsx: Komponen React utama aplikasi anda. Anda boleh mula membina UI anda di sini.
  • vite.config.js: Fail konfigurasi Vite yang membolehkan anda menyesuaikan proses binaan anda, menambah pemalam dan banyak lagi.

Struktur ini direka bentuk untuk menjadi minimum tetapi berkuasa, memberikan anda asas yang kukuh untuk mula membina aplikasi React anda tanpa kerumitan yang tidak perlu. Anda boleh mengembangkan dan menyesuaikan struktur dengan mudah sambil projek anda berkembang.

Memahami Struktur Projek

Apabila anda memulakan projek React menggunakan Vite, ia mewujudkan struktur projek yang bersih dan minimum. Struktur ini direka bentuk untuk membantu anda bermula dengan cepat tanpa overhed fail yang tidak perlu atau konfigurasi kompleks. Mari pecahkan fail dan folder utama yang dibuat oleh Vite untuk membantu anda memahami persediaan.

my-app
├── node_modules
├── src
├── .eslintrc.cjs
├── index.html
├── README.md
├── package.json
└── vite.config.js
Nach dem Login kopieren

Pecahan Fail dan Folder Utama

  1. index.html: Fail ini ialah titik masuk aplikasi anda dan terletak dalam direktori akar. Tidak seperti pengikat tradisional, Vite menyediakan terus fail HTML ini semasa pembangunan. Di sinilah aplikasi React anda dipasang dan Vite menyuntik skrip yang diperlukan untuk memuatkan apl itu.

  2. src/: Folder src mengandungi semua kod aplikasi anda.

  3. main.jsx: Ini ialah titik masuk utama untuk apl React anda. Ia mengimport React, memaparkan komponen akar (App.jsx) dan melampirkannya pada elemen #root dalam fail index.html.

  4. App.jsx: Ini ialah komponen akar aplikasi anda, tempat anda akan mula membina UI anda. Anda boleh mengubah suai fail ini untuk menambah lebih banyak komponen apabila projek anda berkembang.

  5. vite.config.js: Fail ini mengandungi konfigurasi Vite. Ia membolehkan anda menyesuaikan gelagat Vite, menambah pemalam atau mengubah suai proses binaan, tetapi untuk kebanyakan projek kecil, anda mungkin tidak perlu menyentuh fail ini.

Fail Utama

  1. index.html : Fail HTML tempat apl React anda disuntik. Ia mengandungi satu
    elemen dengan id="root" tempat apl React akan dipasang.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
Nach dem Login kopieren
  1. src/main.jsx Titik masuk JavaScript utama untuk aplikasi React anda. Ia menjadikan komponen Apl ke dalam div #root index.html.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
Nach dem Login kopieren
  1. src/App.jsx : Komponen utama apl React anda. Di sinilah anda akan mula membina UI anda. Secara lalai, ia termasuk komponen React yang mudah, tetapi anda boleh mengubah suainya agar sesuai dengan keperluan anda.
import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to Vite + React!</h1>
    </div>
  );
}

export default App;
Nach dem Login kopieren

Mengubah suai App.jsx untuk Mencipta Komponen Reaksi Mudah

Mari ubah suai komponen App.jsx lalai untuk mencipta komponen React mudah yang memaparkan senarai item:

import React from 'react';

function App() {
  const items = ['Item 1', 'Item 2', 'Item 3'];

  return (
    <div>
      <h1>Simple List with Vite and React</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Nach dem Login kopieren

Dalam contoh ini:

  • We define an array items with a few sample items.
  • We use the map() function to iterate over the items array and render each item as a list item (
  • ).

This project structure offers flexibility and simplicity, allowing you to grow your application easily as you continue development.

Working with Vite in a React Project

Vite simplifies the process of working with assets, styles, and offers fast feedback during development through Hot Module Replacement (HMR). Let’s walk through how to handle these features in your Vite-React project.

Importing and Using Assets (Images, Styles)

Vite allows you to easily import assets such as images or CSS files directly into your React components, with the benefit of bundling them efficiently during the build.

import React from 'react';
import logo from './assets/logo.png'; // Importing an image

function App() {
  return (
    <div>
      <img src={logo} alt="App Logo" />
      <h1>Welcome to Vite React App!</h1>
    </div>
  );
}

export default App;
Nach dem Login kopieren

In this example, Vite processes the logo.png image file and ensures it’s bundled efficiently when you build the project. During development, the image is served directly without bundling, contributing to faster reload times.

import React from 'react';
import './App.css'; // Importing a CSS file

function App() {
  return (
    <div className="app-container">
      <h1>Welcome to Vite React App!</h1>
    </div>
  );
}

export default App;
Nach dem Login kopieren

How Vite Handles Hot Module Replacement (HMR)

One of Vite’s standout features is its fast Hot Module Replacement (HMR). HMR allows you to see changes in your application instantly without a full page reload. When you modify a file, Vite only updates the specific module that was changed, maintaining the application’s state.

For example, if you update a React component:

import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to the updated Vite React App!</h1> {/* Change the text */}
    </div>
  );
}

export default App;
Nach dem Login kopieren

Upon saving the file, Vite’s HMR immediately updates the UI without a full page reload. This speeds up the development process significantly, especially when you are working on UI components or tweaking styles.

Troubleshooting Common Issues

While Vite generally offers a smooth development experience, you might still run into a few common issues when using it with React. Here are some of those issues and how to fix them, along with tips for optimizing performance and build times.

  1. Error: "Failed to resolve module"

    This is a common issue that occurs when Vite cannot resolve a module you’re trying to import, especially when dealing with third-party libraries or incorrect paths.
    Solution:

  • Double-check the import paths in your code. Ensure you are importing the correct file or module.
  • For third-party libraries, try reinstalling the dependencies:
  npm install
Nach dem Login kopieren
  • If the issue persists, clear Vite’s cache and restart the server

    rm -rf node_modules/.vite
    npm run dev
    
    Nach dem Login kopieren
  1. Error: "React Refresh failed" Vite uses React Fast Refresh to enable Hot Module Replacement (HMR). Sometimes, this can fail, particularly when the React version is mismatched or there’s a configuration issue.

Solution:

  • Make sure that you're using a supported version of React (17.x or later).

  • Ensure that @vitejs/plugin-react is correctly installed and added to your vite.config.js file:

npm install @vitejs/plugin-react --save-dev
Nach dem Login kopieren

In vite.config.js:

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

export default {
  plugins: [react()],
};
Nach dem Login kopieren
  • Restart your Vite development server after applying these fixes.
  1. Assets Not Loading After

    If assets like images, fonts, or other static files are not loading properly after building the app, it’s often due to incorrect asset paths.

Solution:

  • Make sure that you're using relative paths for your assets. For example, use ./assets/logo.png instead of /assets/logo.png.
  • Check yourvite.config.js for the correct base path. If your app is deployed in a subdirectory, you may need to set the base option:

    export default {
    base: '/subdirectory/',
    };
    
    Nach dem Login kopieren

Following these troubleshooting steps should help you resolve common issues and ensure your Vite + React project runs smoothly.

Conclusion

In this guide, we walked through setting up a React project with Vite, explored its project structure, imported assets, and styles, and highlighted how Vite's fast Hot Module Replacement (HMR) enhances development. You’ve also learned some common troubleshooting tips and optimizations for build performance.

Vite’s speed and simplicity make it a powerful tool, whether you’re working on small projects or scaling up to larger ones. As you continue to explore Vite, dive into its advanced features, such as plugins and environment-specific configurations, to make your development experience even better.

Das obige ist der detaillierte Inhalt vonEin Anfängerleitfaden zur Verwendung von Vite mit React. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!