首頁 > web前端 > js教程 > 主體

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

王林
發布: 2024-09-05 22:33:33
原創
880 人瀏覽過

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 應用程式。
    <!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>
    
    登入後複製
    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(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    
    登入後複製
    1. src/App.jsx :React 應用程式的主要元件。您將在此處開始建立 UI。預設情況下,它包含一個簡單的 React 元件,但您可以對其進行修改以滿足您的需求。
    import React from 'react';
    
    function App() {
      return (
        <div>
          <h1>Welcome to Vite + React!</h1>
        </div>
      );
    }
    
    export default App;
    
    登入後複製

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

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

    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;
    
    登入後複製

    在此範例中:

    • 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;
    
    登入後複製

    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;
    
    登入後複製

    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;
    
    登入後複製

    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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!