首頁  >  文章  >  web前端  >  教學:如何使用 Vite 建立 React 應用

教學:如何使用 Vite 建立 React 應用

DDD
DDD原創
2024-10-11 10:29:01339瀏覽

一、簡介

在 JavaScript 前端世界中,不斷有新的工具來建構和最佳化專案。 React 是一種用於建立使用者介面的流行 JavaScript 程式庫,傳統上與 Create-React-App (CRA) 一起使用以簡化設定和開發。然而,一種名為 Vite 的新工具因其速度和效率而迅速獲得關注,為 CRA 提供了現代替代品。

在這篇文章中,我們將首先介紹使 Vite 成為 React 開發人員的絕佳選擇的具體功能,然後我們將仔細研究 Create-React-App。之後,我們將比較這兩種工具,幫助您決定何時使用每種工具以及何時從 CRA 切換到 Vite。

無論您是開始一個新的 React 項目還是考慮遷移現有項目,我們都會引導您完成整個過程,幫助您選擇最適合您需求的工具。此外,我們將為想要充分利用 Vite 和 React 設定的人探索進階配置和最佳化技術。

讀完本文,您將獲得以下關鍵問題的答案:

  1. Vite 有哪些獨特功能使其成為 React 開發的絕佳選擇?

  2. Create-React-App 與 Vite 在效能、配置和靈活性方面相比如何?

  3. 什麼時候該堅持使用 Create-React-App,什麼時候改用 Vite 比較好?

  4. 使用 Vite 建立一個新的 React 專案需要哪些步驟?

  5. 如何將現有的 Create-React-App 專案移轉到 Vite?

  6. 您可以應用哪些進階配置和最佳化技術來充分利用 Vite 和 React 設定?

2.什麼是Vite?

Tutorial: How to Create a React App with Vite

Vite 是一款旨在讓 Web 開發更快、更有效率的建置工具。 “Vite”這個名字來自法語單字“快”。 Vite 由 Vue.js 的開發者 Evan You 創建,旨在解決 Webpack 等傳統捆綁器的效能限制。

它提供對 React、Vue 和 Svelte 等流行框架的支援。其靈活性使其能夠相容於多種前端技術,確保能夠適應各種開發需求。它利用本機 ECMAScript 模組和現代瀏覽器功能來提供快速開發環境。

無論您是建立簡單的 React 應用程式還是複雜的 Web 應用程序,Vite 都能提供簡化的體驗,從而節省您的時間。

2.1 為什麼創建Vite?

像 Webpack 這樣的傳統建置工具已經存在多年,並且為開發者社群提供了良好的服務。然而,隨著 Web 應用程式變得越來越複雜,啟動開發伺服器並查看瀏覽器中反映的變更所需的時間也越來越長。

下圖描述了傳統的捆綁方法。這個過程從連接到應用程式的各種路由和模組的入口點開始。在伺服器準備好使用之前,所有這些元件都捆綁在一起。這種預先捆綁非常耗時,尤其是隨著應用程式的成長,導致開發伺服器的啟動時間更長。

Tutorial: How to Create a React App with Vite

Vite 在開發過程中採用不同的方法來建立和服務您的應用程式。伺服器幾乎立即準備就緒,而不是預先捆綁所有內容,並且瀏覽器僅在需要時請求所需的特定模組。這是透過原生 ES 模組 (ESM) 支援實現的,它允許動態導入、實現程式碼分割並減少在任何給定時間需要處理的程式碼量。透過只提供必要的服務,Vite 確保了更快的回饋循環,讓開發者能夠更有效率地工作。

Tutorial: How to Create a React App with Vite

2.2 Vite主要特點

以下是Vite的核心功能:

  • 即時伺服器啟動:
    使用傳統工具,啟動開發伺服器可能需要一段時間,尤其是對於大型專案。然而,Vite 幾乎立即啟動。它僅透過轉換您目前正在處理的程式碼而不是整個專案來實現此目的。這使您的開發體驗更加順暢且反應更快。

  • Blitzschneller Austausch heißer Module (HMR):
    Mit Hot Module Replacement (HMR) können Sie die Ergebnisse Ihrer Codeänderungen in Echtzeit sehen, ohne den Browser aktualisieren zu müssen. Der HMR von Vite ist unglaublich schnell, da er nur die spezifischen Module aktualisiert, die geändert wurden, und nicht die gesamte Anwendung. Diese sofortige Feedbackschleife sorgt für einen viel effizienteren Entwicklungsprozess.

  • Unterstützung für native ES-Module:
    Vite nutzt die native ES-Modulunterstützung, die in moderne Browser integriert ist. Anstatt Ihre gesamte Codebasis in ein paar großen Dateien zu bündeln (wie bei herkömmlichen Tools), stellt Vite jedes Modul als separate Datei bereit. Dies reduziert den Bedarf an komplexen Transformationen und beschleunigt sowohl das anfängliche Laden als auch nachfolgende Updates.

  • Optimierter Build-Prozess mithilfe von Rollup:
    Auch in der Produktion ist Vite leistungsstark. Wenn Sie zur Bereitstellung bereit sind, bündelt Vite Ihren Code mithilfe von Rollup, einem modernen Modul-Bundler, effizient. Das bedeutet, dass Sie das Beste aus beiden Welten erhalten: schnelle Entwicklung und optimierte Produktionsaufbauten.

  • Flexible Konfiguration in vite.config.js:
    Vite ist hochgradig anpassbar. Mit einer unkomplizierten Konfigurationsdatei (vite.config.js) können Sie die Einstellungen ganz einfach an die Anforderungen Ihres Projekts anpassen. Egal, ob Sie Umgebungsvariablen einrichten, Pfadaliase konfigurieren oder Plugins hinzufügen müssen, Vite macht es Ihnen einfach.

  • Native TypeScript-Unterstützung:
    Sowohl React als auch Vite unterstützen TypeScript nativ, sodass Sie statische Typisierung problemlos in Ihren Code integrieren können. Die Verwendung von TypeScript trägt dazu bei, Fehler früher im Entwicklungsprozess zu erkennen und die Wartbarkeit des Codes zu verbessern.

3. Was ist Create-React-App?

Create-React-App (CRA) ist ein beliebtes von Facebook entwickeltes Tool, das den Prozess der Einrichtung eines neuen React-Projekts vereinfacht. Es ermöglicht Entwicklern, schnell mit der Erstellung von React-Anwendungen zu beginnen, ohne dass eine Entwicklungsumgebung manuell konfiguriert werden muss.

3.1 Warum wurde die Create-React-App erstellt?

Vor CRA erforderte die Einrichtung eines React-Projekts die Konfiguration einer Vielzahl von Tools, was insbesondere für React-Neulinge eine entmutigende Aufgabe sein konnte. Um dieser Herausforderung zu begegnen, wurde 2016 CRA als Lösung eingeführt, die eine Konfiguration ohne Konfiguration ermöglicht. Dieses Tool ermöglichte es Entwicklern, direkt mit dem Schreiben von React-Code zu beginnen, ohne sich über die Komplexität von Build-Tools und Konfigurationen Gedanken machen zu müssen.

CRA wurde schnell zum Standardtool für React-Entwickler, da es die Projekteinrichtung rationalisierte und Konsistenz in Entwicklungsumgebungen brachte, wodurch es für Teams einfacher wurde, effektiv zusammenzuarbeiten.

3.2 Hauptfunktionen der Create-React-App

Dies sind die Kernfunktionen von CRA:

  • Erstellung eines Abhängigkeitsbaums mit Webpack:
    CRA verwendet Webpack, um die index.js-Datei Ihres Projekts zu analysieren, die als Einstiegspunkt für Ihre Anwendung fungiert. Webpack erstellt dann einen Abhängigkeitsbaum, indem es alle Module, die Ihr Projekt benötigt, miteinander verknüpft. Dieser automatisierte Prozess stellt sicher, dass Ihre Anwendung über alle erforderlichen Ressourcen gebündelt verfügt.

  • Code-Transpilation mit Babel:
    Sobald der Abhängigkeitsbaum erstellt ist, verwendet CRA Babel, um Ihr modernes JavaScript in eine Version zu transpilieren, die mit einer größeren Auswahl an Browsern kompatibel ist. Dieser Schritt stellt sicher, dass Ihre App in verschiedenen Umgebungen reibungslos ausgeführt werden kann, unabhängig davon, ob diese die neuesten JavaScript-Funktionen unterstützen.

  • Codebündelung und -bereitstellung:
    Nach der Transpilierung bündelt Webpack den Code Ihrer Anwendung in einige komprimierte Dateien. Diese Bundles werden dann über einen Webserver bereitgestellt, sodass Ihre App über einen lokalen Entwicklungsserver zugänglich ist.

  • Keine Konfiguration erforderlich:
    Einer der größten Vorteile von CRA besteht darin, dass es ein voll funktionsfähiges React-Setup bietet. Wenn Sie mit CRA ein neues Projekt erstellen, richtet es automatisch alles ein, was Sie benötigen, wie Webpack für die Bündelung, Babel für die Transpilierung von modernem JavaScript und ESLint für Linting. Das bedeutet, dass Sie sofort mit dem Codieren beginnen können, ohne Zeit mit der Konfiguration Ihrer Umgebung zu verbringen.

4. Warum einen Wechsel von Create-React-App zu Vite in Betracht ziehen?

In diesem Abschnitt vergleichen wir Vite und CRA in mehreren Schlüsselbereichen wie Konfiguration, Leistung, Support und Funktionen, um Ihnen dabei zu helfen, festzustellen, wann ein Wechsel von CRA zu Vite sinnvoll sein könnte.

4.1 Vergleich: Vite vs. 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 각 도구를 사용하는 시기와 전환을 고려하는 시기

  1. Create-React-App을 사용하는 경우:
  • 초보자용:
    React나 프론트엔드 개발이 처음이라면 CRA가 좋은 출발점입니다. 예를 들어, 간단한 포트폴리오 웹사이트나 개인 블로그를 구축하는 경우 구성이 필요 없는 접근 방식을 사용하면 기본 설정에 대해 걱정하지 않고 React 학습에 집중할 수 있습니다.

  • 중소 규모 프로젝트의 경우:
    CRA는 성능이나 구성을 미세 조정하는 것보다 설정 및 사용의 단순성이 더 중요한 소규모 프로젝트에 적합합니다. 예를 들어 CRA는 회사 내부 대시보드나 소규모 전자상거래 사이트와 같은 프로젝트에 적합합니다.

  • 안정성을 위해:
    학교 관리 시스템이나 조직의 웹 사이트와 같이 안정적이고 널리 지원되는 도구가 필요한 장기 프로젝트를 개발하는 경우 CRA의 대규모 커뮤니티와 강력한 문서가 신뢰할 수 있는 선택이 됩니다. 잦은 변경 사항에 대해 걱정할 필요가 없으며 커뮤니티의 지원을 받을 수 있습니다.

  1. Vite 사용 시기:
  • 속도와 성능:
    소셜 미디어 플랫폼이나 복잡한 데이터 시각화 대시보드와 같은 대규모 애플리케이션에서 작업하는 경우 Vite의 속도가 매우 중요합니다. 예를 들어 앱에 수많은 페이지나 구성 요소가 포함되어 있는 경우 Vite의 빠른 빌드 시간과 효율적인 HMR(핫 모듈 교체)을 통해 개발 중에 업데이트를 기다리는 데 소요되는 시간을 줄일 수 있습니다.

  • 현대 개발 방식:
    프로젝트가 ES 모듈 사용과 같은 최신 JavaScript 방식을 기반으로 하거나 Svelte와 같은 최첨단 라이브러리 또는 TypeScript를 사용하여 통합하는 경우 Vite는 작업 흐름을 간소화할 수 있는 기본 지원을 제공합니다. 최신 웹 표준과 기능을 최신 상태로 유지해야 하는 최신 SaaS 플랫폼을 개발하는 것이 그 예입니다.

  • 유연성:
    특정 산업에 맞춰진 CMS와 같은 고도로 맞춤화된 애플리케이션을 구축하는 경우 Vite의 플러그인 시스템과 모듈식 아키텍처를 사용하면 Tailwind CSS, Preact 또는 필요에 맞는 기타 도구를 쉽게 통합할 수 있습니다. 이러한 유연성은 특정 요구 사항을 충족하기 위해 기본 구성을 크게 조정해야 하는 애플리케이션에 특히 유용합니다.

  1. CRA에서 Vite로 전환을 고려해야 하는 경우:
  • 프로젝트 및 사용자 기반이 크게 성장하기 시작합니다:
    CRA로 시작하여 소규모 프로젝트 관리 도구를 구축한다고 상상해 보세요. 더 많은 기능이 추가되고 사용자 기반이 늘어남에 따라 빌드 시간과 개발 서버 시작 시간이 크게 늘어난다는 것을 알 수 있습니다. 이 시점에서 Vite로 전환하면 빠른 개발 주기를 유지하는 데 도움이 되어 새로운 기능을 더 효율적으로 추가할 수 있습니다.

  • 훌륭한 개발자 경험을 원합니다:
    개발 중 신속한 피드백이 중요한 실시간 협업 앱을 작업하고 있다고 가정해 보겠습니다. 앱 복잡성이 증가하면 CRA 속도가 느려질 수 있습니다. Vite로 전환하면 더 빠른 서버 시작과 HMR의 이점을 누릴 수 있어 개발 프로세스의 반응성이 더욱 향상됩니다.

  • 현대적인 도구로 앞서 나가려면:
    최신 웹 개발 사례를 소개해야 하는 튜토리얼 사이트를 유지 관리하고 있다면 CRA에서 Vite로 전환하는 것이 도움이 될 수 있습니다. 이 스위치를 사용하면 최신 도구와 방법을 시연하여 미래를 내다보는 시청자에게 콘텐츠의 관련성과 정보를 유지하는 데 도움이 됩니다.

5. Vite 및 React 시작하기

이 섹션에서는 Vite를 React와 함께 사용하는 두 가지 접근 방식을 안내합니다. 새 프로젝트를 시작하든 기존 CRA(Create-React-App) 프로젝트를 Vite로 업그레이드하려고 하든 저희가 도와드리겠습니다.

5.1 전제 조건

이 튜토리얼에서는 사용자가 React와 JavaScript에 대한 기본적인 이해가 있다고 가정합니다. 시작하려면 컴퓨터에 Node.js와 NPM이 설치되어 있는지 확인하세요.

5.2 Vite를 사용하여 React 프로젝트 설정

Vite를 사용하여 새로운 React 프로젝트를 시작하는 것은 빠르고 간단합니다. 전체 코드를 보려면 GitHub에서 Vite 저장소가 포함된 React 애플리케이션을 확인하세요.

시작하는 방법은 다음과 같습니다.

1. 새로운 Vite 프로젝트 생성

먼저 터미널을 열고 다음 명령을 실행하여 React를 템플릿으로 사용하여 새 Vite 프로젝트를 만듭니다.

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

2. 프로젝트 디렉토리로 이동

프로젝트가 생성된 후 프로젝트 디렉터리로 이동하세요.

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.

以上是教學:如何使用 Vite 建立 React 應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn