Rumah  >  Artikel  >  hujung hadapan web  >  Tutorial: Cara Membuat Apl React dengan Vite

Tutorial: Cara Membuat Apl React dengan Vite

DDD
DDDasal
2024-10-11 10:29:01334semak imbas

1. Pengenalan

Dalam dunia bahagian hadapan JavaScript, sentiasa ada alatan baharu untuk membina dan mengoptimumkan projek yang muncul. React, perpustakaan JavaScript yang popular untuk membina antara muka pengguna, secara tradisinya telah dipasangkan dengan Create-React-App (CRA) untuk memudahkan persediaan dan pembangunan. Walau bagaimanapun, alat yang lebih baharu yang dipanggil Vite semakin mendapat tarikan kerana kelajuan dan kecekapannya, menawarkan alternatif moden kepada CRA.

Dalam catatan blog ini, kami akan mulakan dengan mempersembahkan ciri khusus yang menjadikan Vite pilihan terbaik untuk pembangun React, dan kemudian kami akan melihat lebih dekat pada Create-React-App. Selepas itu, kami akan membandingkan dua alatan untuk membantu anda memutuskan masa untuk menggunakan setiap satu dan masa untuk beralih daripada CRA kepada Vite.

Sama ada anda memulakan projek React baharu atau mempertimbangkan untuk memindahkan projek sedia ada, kami akan membimbing anda melalui proses tersebut, membantu anda memilih alat terbaik untuk keperluan anda. Selain itu, kami akan meneroka konfigurasi lanjutan dan teknik pengoptimuman untuk mereka yang ingin memanfaatkan sepenuhnya persediaan Vite dan React mereka.

Menjelang akhir siaran ini, anda akan mendapat jawapan kepada soalan penting berikut:

  1. Apakah ciri unik Vite yang menjadikannya pilihan terbaik untuk pembangunan React?

  2. Bagaimanakah Create-React-App dibandingkan dengan Vite dari segi prestasi, konfigurasi dan fleksibiliti?

  3. Bilakah anda harus menggunakan Create-React-App, dan bilakah lebih baik untuk beralih kepada Vite?

  4. Apakah langkah yang terlibat dalam menyediakan projek React baharu dengan Vite?

  5. Bagaimanakah anda boleh memindahkan projek Create-React-App sedia ada ke Vite?

  6. Apakah konfigurasi lanjutan dan teknik pengoptimuman yang boleh anda gunakan untuk memanfaatkan sepenuhnya persediaan Vite dan React anda?

2. Apa itu Vite?

Tutorial: How to Create a React App with Vite

Vite ialah alat binaan yang direka untuk menjadikan pembangunan web lebih pantas dan cekap. Nama "Vite" berasal dari perkataan Perancis untuk "cepat". Dicipta oleh Evan You, pembangun yang sama di belakang Vue.js, Vite telah direka untuk menangani had prestasi pengikat tradisional seperti Webpack.

Ia menawarkan sokongan untuk rangka kerja popular seperti React, Vue dan Svelte. Fleksibilitinya menjadikannya serasi dengan pelbagai jenis teknologi hadapan, memastikan ia boleh menyesuaikan diri dengan pelbagai keperluan pembangunan. Ia memanfaatkan modul ECMAScript asli dan keupayaan penyemak imbas moden untuk menyediakan persekitaran pembangunan yang pantas.

Tidak kira sama ada anda sedang membina apl React yang ringkas atau aplikasi web yang kompleks, Vite menawarkan pengalaman diperkemas yang boleh menjimatkan masa anda.

2.1 Mengapa Vite Dicipta?

Alat binaan tradisional seperti Webpack telah wujud selama bertahun-tahun dan telah berkhidmat dengan baik kepada komuniti pembangun. Walau bagaimanapun, apabila aplikasi web berkembang dalam kerumitan, begitu juga masa yang diambil untuk memulakan pelayan pembangunan dan melihat perubahan yang ditunjukkan dalam penyemak imbas.

Imej berikut menerangkan pendekatan penggabungan tradisional. Proses bermula dengan titik masuk yang menghubungkan ke pelbagai laluan dan modul aplikasi. Semua komponen ini digabungkan bersama sebelum pelayan sedia untuk digunakan. Himpunan pendahuluan ini memakan masa, terutamanya apabila aplikasi berkembang, membawa kepada masa permulaan yang lebih lama untuk pelayan pembangunan.

Tutorial: How to Create a React App with Vite

Vite mengambil pendekatan berbeza untuk membina dan menyampaikan aplikasi anda semasa pembangunan. Daripada menggabungkan segala-galanya terlebih dahulu, pelayan bersedia hampir serta-merta, dan penyemak imbas hanya meminta modul khusus yang diperlukan apabila ia diperlukan. Ini dimungkinkan melalui sokongan modul ES asli (ESM), yang membolehkan import dinamik, membolehkan pemisahan kod dan mengurangkan jumlah kod yang perlu diproses pada bila-bila masa. Dengan menyediakan hanya apa yang perlu, Vite memastikan gelung maklum balas yang lebih pantas, membolehkan pembangun berfungsi dengan lebih cekap.

Tutorial: How to Create a React App with Vite

2.2 Ciri-ciri Utama Vite

Ini adalah ciri teras Vite:

  • Mula Pelayan Segera:
    Dengan alat tradisional, memulakan pelayan pembangunan boleh mengambil sedikit masa, terutamanya untuk projek besar. Vite, bagaimanapun, bermula hampir serta-merta. Ia melakukan ini dengan hanya mengubah kod yang sedang anda kerjakan, bukan keseluruhan projek. Ini menjadikan pengalaman pembangunan anda lebih lancar dan lebih responsif.

  • 閃電般的快速熱模組更換 (HMR):
    熱模組替換 (HMR) 可讓您即時查看程式碼變更的結果,而無需刷新瀏覽器。 Vite 的 HMR 速度非常快,因為它只更新發生更改的特定模組,而不是整個應用程式。這種即時回饋循環使開發過程更加有效率。

  • 支援原生 ES 模組:
    Vite 利用現代瀏覽器內建的原生 ES 模組支援。 Vite 不是將整個程式碼庫捆綁到幾個大檔案中(與傳統工具一樣),而是將每個模組作為單獨的檔案提供。這減少了對複雜轉換的需求,並加快了初始載入和後續更新的速度。

  • 使用 Rollup 最佳化建置流程:
    Vite在生產上也很強大。當您準備好部署時,Vite 使用現代模組捆綁器 Rollup 有效地捆綁您的程式碼。這意味著您可以兩全其美:快速開發和優化的生產構建。

  • vite.config.js中的靈活設定:
    Vite 是高度可自訂的。透過簡單的設定檔 (vite.config.js),您可以輕鬆調整設定以滿足專案的需求。無論您是需要設定環境變數、配置路徑別名,還是添加插件,Vite 都讓一切變得簡單。

  • 原生 TypeScript 支援:
    React 和 Vite 本身都支援 TypeScript,因此可以輕鬆地將靜態類型合併到程式碼中。使用 TypeScript 有助於在開發過程的早期捕獲錯誤並增強程式碼的可維護性。

3.什麼是Create-React-App?

Create-React-App (CRA) 是 Facebook 開發的一款流行工具,它簡化了建立新 React 專案的過程。它允許開發者快速開始建立 React 應用程序,而無需手動配置開發環境。

3.1 為什麼要建立Create-React-App?

在 CRA 之前,建立 React 專案需要配置各種工具,這可能是一項艱鉅的任務,特別是對於 React 新手來說。為了應對這項挑戰,CRA 於 2016 年推出,作為提供零配置設定的解決方案。該工具使開發人員能夠直接編寫 React 程式碼,而無需擔心建置工具和配置的複雜性。

CRA 迅速成為 React 開發人員的標準工具,因為它簡化了專案設定並為開發環境帶來了一致性,使團隊更容易有效協作。

3.2 Create-React-App 的主要特性

以下是 CRA 的核心功能:

  • 使用 Webpack 建立依賴樹:
    CRA 使用 Webpack 分析專案的 index.js 文件,該文件充當應用程式的入口點。然後,Webpack 透過將專案所需的所有模組連結在一起來建立依賴關係樹。這個自動化過程可確保您的應用程式將所有必要的資源捆綁在一起。

  • 使用 Babel 進行代碼轉譯:
    一旦建立了依賴關係樹,CRA 就會使用 Babel 將現代 JavaScript 轉換為與更廣泛的瀏覽器相容的版本。此步驟可確保您的應用程式可以在不同環境中順利運行,無論它們是否支援最新的 JavaScript 功能。

  • 程式碼捆綁與服務:
    轉譯後,Webpack 將應用程式的程式碼捆綁到幾個壓縮檔案中。然後透過網頁伺服器提供這些捆綁包,使您的應用程式可以透過本機開發伺服器存取。

  • 無設定:
    CRA 的最大優點之一是它提供了功能齊全的 React 設定。當您使用 CRA 建立新專案時,它會自動設定您所需的一切,例如用於捆綁的 Webpack、用於轉換現代 JavaScript 的 Babel 以及用於 linting 的 ESLint。這意味著您可以立即開始編碼,而無需花時間配置環境。

4. 為什麼要考慮從 Create-React-App 切換到 Vite?

在本節中,我們將在配置、效能、支援和功能等幾個關鍵領域對 Vite 和 CRA 進行比較,以幫助您確定何時從 CRA 切換到 Vite 是有意義的。

4.1 比較:Vite 與 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)可以減少您在開發過程中等待更新的時間。

  • 現代開發實務:
    如果您的專案是基於現代 JavaScript 實踐(例如使用 ES 模組),或者如果您正在與 Svelte 等尖端庫整合或使用 TypeScript,Vite 提供開箱即用的支持,可以簡化您的工作流程。一個例子是開發一個現代 SaaS 平台,您需要在其中了解最新的 Web 標準和功能。

  • 為了靈活性:
    如果您正在建立高度客製化的應用程序,例如為特定行業量身定制的 CMS,Vite 的插件系統和模組化架構可讓您輕鬆整合 Tailwind CSS、Preact 或其他適合您需求的工具。這種靈活性對於預設配置需要進行重大調整以滿足特定要求的應用程式特別有用。

  1. 何時考慮從 CRA 切換到 Vite:
  • 您的專案和使用者群開始顯著成長:
    想像一下從 CRA 開始建立一個小型專案管理工具。隨著更多功能的添加和用戶群的增長,您可能會注意到建置時間和開發伺服器啟動時間顯著增加。此時,切換到 Vite 可以幫助您保持快速的開發週期,讓您更有效率地新增功能。

  • 您正在尋求卓越的開發者體驗:
    假設您正在開發一個即時協作應用程序,其中開發過程中的快速回饋至關重要。隨著應用程式複雜性的增加,CRA 可能會變慢。透過切換到 Vite,您可以受益於其更快的伺服器啟動和 HMR,從而實現更靈敏的開發過程。

  • 利用現代工具保持領先:
    如果您正在維護一個需要展示最新 Web 開發實務的教學網站,那麼從 CRA 過渡到 Vite 可能會有所幫助。透過此開關,您可以示範現代工具和方法,幫助您的內容為具有前瞻性的受眾保持相關性和資訊性。

5. Vite 和 React 入門

在本節中,我們將引導您了解將 Vite 與 React 結合使用的兩種不同方法。無論您是要開始一個新專案還是希望將現有的 Create-React-App (CRA) 專案升級到 Vite,我們都能滿足您的需求。

5.1 先決條件

本教學假設您對 React 和 JavaScript 有基本的了解。首先,請確保您的電腦上安裝了 Node.js 和 NPM。

5.2 使用Vite建立React項目

使用 Vite 啟動新的 React 專案既快速又簡單。如果您想查看完整的程式碼,請查看 GitHub 上的 React Application with Vite 儲存庫。

以下是您如何開始:

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.

Atas ialah kandungan terperinci Tutorial: Cara Membuat Apl React dengan Vite. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn