首頁  >  文章  >  web前端  >  將 Vite 與 React 結合使用的初學者指南

將 Vite 與 React 結合使用的初學者指南

王林
王林原創
2024-09-05 22:33:33883瀏覽

A beginners guide to using Vite with React

介紹

開始新的 React 專案時,選擇正確的工具會對您的工作流程產生重大影響。雖然 Webpack 等工具已廣泛使用多年,但 Vite 等新選項提供了更快、更有效率的替代方案。

Vite 由 Evan You(Vue.js 的創建者)開發,旨在提供閃電般的快速開發環境。它透過本機 ES 模組提供檔案並使用最佳化的開發伺服器來實現這一點。這可以縮短伺服器啟動時間並提高開發回應速度。

React 是建立使用者介面最受歡迎的程式庫之一,可與 Vite 無縫協作。其基於元件的架構非常適合開發動態單頁應用程式 (SPA)。這就是為什麼 Vite 是 React 專案的絕佳選擇:

  • 即時伺服器啟動:與傳統捆綁器不同,Vite 的開發伺服器幾乎立即啟動,將檔案作為原生 ES 模組提供服務,避免了開發過程中的捆綁。

  • 快速熱模組替換(HMR):Vite 的 HMR 速度非常快,讓您幾乎可以立即看到 React 組件的變化,從而加快開發速度。

  • 最佳化生產版本:對於生產,Vite 使用 Rollup 來最佳化您的套裝。它包括自動程式碼分割等功能,可縮短應用程式的載入時間。

  • 現代開發支援:Vite 與 TypeScript、JSX 等現代 JavaScript 工具和 Sass 等 CSS 預處理器配合良好,提供開箱即用的尖端開發體驗。

在本部落格中,我們將指導您使用 Vite 設定 React 項目,探索專案的結構,並向您展示如何使用資產和部署應用程式。最後,您將看到 Vite 如何改善您的 React 開發體驗。

什麼是維特?

Vite 是一款專為速度和效率而設計的現代構建工具,特別是在使用 React 等 JavaScript 框架時。 Vite 由 Vue.js 的創作者 Evan You 開發,因其能夠提供快速、簡化的開發體驗而脫穎而出。

Vite主要特點

  1. 即時伺服器啟動:Vite 透過原生 ES 模組提供文件,允許開發伺服器幾乎立即啟動,即使對於大型專案也是如此。

  2. 快速熱模組替換(HMR):Vite 的 HMR 非常快,可以在您開發時近乎即時地更新您的 React 元件。

  3. 最佳化構建:Vite 使用 Rollup 進行生產構建,透過程式碼分割和樹搖動等功能確保高效捆綁。

  4. 現代 JavaScript 支援:Vite 內建了對最新 JavaScript 功能的支持,包括 TypeScript、JSX 和 Sass 等 CSS 預處理器。

Vite 與 Webpack

雖然 Webpack 多年來一直是流行的選擇,但它通常需要複雜的配置,並且由於其捆綁過程,在開發過程中可能會比較慢。相較之下,Vite 簡化了設定過程並在開發過程中跳過捆綁,從而縮短了伺服器啟動時間和 HMR。 Vite 的生產版本也經過高度優化,與 Webpack 非常相似,但配置更簡單。

為什麼將 Vite 與 React 結合使用?

  1. 速度:Vite 快速的伺服器啟動和 HMR 使開發 React 應用程式變得更容易,無需等待漫長的捆綁過程。

  2. 簡單:Vite 易於使用的設定讓您專注於建立 React 元件,而不是設定建置工具。

  3. 效率:Vite 確保您的 React 應用不僅可以快速開發,而​​且可以輕鬆地針對生產進行最佳化。

Vite 為 Webpack 等傳統打包器提供了更現代、更有效率的替代方案,非常適合優先考慮速度和簡單性的 React 專案。

設定開發環境

在使用 React 深入研究 Vite 之前,您需要確保系統上安裝了 Node.js 和 npm。如果您尚未安裝它們,請按照以下步驟開始。

安裝 Node.js 和 npm

要安裝 Node.js 和 npm,請造訪 Node.js 官方網站並下載最新的穩定版本。安裝後,您可以透過在終端機中執行以下命令來驗證安裝:

node -v
npm -v

這些指令應顯示已安裝的 Node.js 和 npm 版本,確認它們設定正確。

初始化一個新的Vite項目

準備好 Node.js 和 npm 後,現在可以使用 Vite 建立新的 React 專案。 Vite 提供了一個簡單的指令來快速建立新專案。開啟終端機並執行以下命令:

npm create vite@latest my-react-app --template react
cd my-react-app
npm install
  • npm create vite@latest my-react-app --template react:此指令使用 React 範本初始化一個新的 Vite 專案。將 my-react-app 替換為您想要的項目名稱。
  • cd my-react-app:導航到新建立的專案目錄。
  • npm install:為您的 React 專案安裝必要的依賴項。

運行開發伺服器

專案設定完畢並安裝依賴項後,您就可以啟動開發伺服器。 Vite 的伺服器很快,你會看到它啟動的速度:

npm run  dev

執行此命令將啟動 Vite 開發伺服器並在預設 Web 瀏覽器中開啟新的 React 應用程式。由於 Vite 的快速熱模組替換 (HMR) 功能,應用程式將在您更改程式碼時自動重新載入。

執行此命令將啟動 Vite 開發伺服器並在預設 Web 瀏覽器中開啟新的 React 應用程式。由於 Vite 的快速熱模組替換 (HMR) 功能,應用程式將在您更改程式碼時自動重新載入。

了解專案結構

Vite 建立了一個簡單且有組織的專案架構。以下是關鍵文件和資料夾的快速概述:

  • index.html:應用程式的入口點。 Vite 將您的腳本注入到此文件中。
  • src/main.jsx:React 應用程式啟動的主 JavaScript 檔案。它通常將根元件 (App.jsx) 渲染到 DOM 中。
  • src/App.jsx:應用程式的主要 React 元件。您可以在這裡開始建立您的 UI。
  • vite.config.js:Vite 的配置文件,您可以在其中自訂建置過程、新增插件等。

這種結構設計得最小但功能強大,為您開始建立 React 應用程式奠定了堅實的基礎,而無需不必要的複雜性。隨著專案的發展,您可以輕鬆擴展和自訂結構。

了解專案結構

當您使用 Vite 初始化 React 專案時,它會建立一個乾淨且最小的專案結構。此結構旨在幫助您快速入門,而無需承擔不必要的文件或複雜配置的開銷。讓我們分解一下 Vite 建立的關鍵檔案和資料夾,以幫助您了解設定。

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

關鍵文件和資料夾的詳細信息

  1. index.html:此檔案是應用程式的入口點,位於根目錄中。與傳統的捆綁器不同,Vite 在開發過程中直接提供該 HTML 檔案。這是你的 React 應用程式安裝的地方,Vite 會注入必要的腳本來載入應用程式。

  2. src/:src 資料夾包含您的所有應用程式程式碼。

  3. main.jsx:這是 React 應用程式的主要入口點。它導入 React,渲染根元件 (App.jsx),並將其附加到 index.html 檔案中的 #root 元素。

  4. App.jsx:這是應用程式的根元件,您將在其中開始建立 UI。隨著專案的成長,您可以修改此文件以添加更多元件。

  5. vite.config.js:此檔案包含Vite的設定。它允許你自訂 Vite 的行為、添加插件或修改建置過程,但對於大多數小型項目,你可能不需要碰觸這個檔案。

關鍵文件

  1. index.html :注入 React 應用程式的 HTML 檔案。它包含一個
    id="root" 的元素將在其中安裝 React 應用程式。
    8b05045a5be5764f313ed5b9168a17e6
    49099650ebdc5f3125501fa170048923
      93f0f5c25f18dab9d176bd4f6de5d30e
        7c8d9f814bcad6a1d7abe4eda5f773e5
        26faf3d1af674280d03ba217d87e9421
        b2386ffb911b14667cb8f0f91ea547a7Vite React App6e916e0f7d1e588d4f442bf645aedb2f
      9c3bca370b5104690d9ef395f2c5f8d1
      6c04bd5ca3fcae76e30b72ad730ca86d
        19bcd4103e1ab0d65154026dcb13abb816b28748ea4df4d9c2150843fecfba68
        ab34d035723b51ae7608c1a5af2465152cacc6d41bbb37262a98f745aa00fbf0
      36cc49f0c466276486e50c850b7e4956
    73a6ac4ed44ffec12cee46588e518a5e
    
    1. src/main.jsx React 應用程式的主要 JavaScript 入口點。它將 App 元件渲染到 index.html 的 #root div 中。
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      e40a65d765d61baa05a126c5d6a7e30a
        a04f3bfb10583669370762b6ad4b2dc1
      db43dfc68f8758907320fe5e4259c7bc
    );
    
    1. src/App.jsx :React 應用程式的主要元件。您將在此處開始建立 UI。預設情況下,它包含一個簡單的 React 元件,但您可以對其進行修改以滿足您的需求。
    import React from 'react';
    
    function App() {
      return (
        dc6dce4a544fdca2df29d5ac0ea9906b
          4a249f0d628e2318394fd9b75b4636b1Welcome to Vite + React!473f0a7621bec819994bb5020d29372a
        16b28748ea4df4d9c2150843fecfba68
      );
    }
    
    export default App;
    

    修改 App.jsx 以建立簡單的 React 元件

    讓我們修改預設的 App.jsx 元件來建立一個顯示項目清單的簡單 React 元件:

    import React from 'react';
    
    function App() {
      const items = ['Item 1', 'Item 2', 'Item 3'];
    
      return (
        dc6dce4a544fdca2df29d5ac0ea9906b
          4a249f0d628e2318394fd9b75b4636b1Simple List with Vite and React473f0a7621bec819994bb5020d29372a
          ff6d136ddc5fdfeffaf53ff6ee95f185
            {items.map((item, index) => (
              ba933d1ba6eb3b125bac48a5e6256165{item}bed06894275b65c1ab86501b08a632eb
            ))}
          929d1f5ca49e04fdcb27f9465b944689
        16b28748ea4df4d9c2150843fecfba68
      );
    }
    
    export default App;
    

    在此範例中:

    • 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 (25edfb22a4f469ecb59f1190150159c6).

    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 (
        dc6dce4a544fdca2df29d5ac0ea9906b
          4ccb2c01b16c2bad77e1308e25ee29fa
          4a249f0d628e2318394fd9b75b4636b1Welcome to Vite React App!473f0a7621bec819994bb5020d29372a
        16b28748ea4df4d9c2150843fecfba68
      );
    }
    
    export default App;
    

    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 (
        11287760be4ea6bfff7670b389046e86
          4a249f0d628e2318394fd9b75b4636b1Welcome to Vite React App!473f0a7621bec819994bb5020d29372a
        16b28748ea4df4d9c2150843fecfba68
      );
    }
    
    export default App;
    

    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 (
        dc6dce4a544fdca2df29d5ac0ea9906b
          4a249f0d628e2318394fd9b75b4636b1Welcome to the updated Vite React App!473f0a7621bec819994bb5020d29372a {/* Change the text */}
        16b28748ea4df4d9c2150843fecfba68
      );
    }
    
    export default App;
    

    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
    
    • If the issue persists, clear Vite’s cache and restart the server

      rm -rf node_modules/.vite
      npm run dev
      
    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
    

    In vite.config.js:

    import react from '@vitejs/plugin-react';
    
    export default {
      plugins: [react()],
    };
    
    • 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/',
      };
      

    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.

以上是將 Vite 與 React 結合使用的初學者指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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