介紹
開始新的 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主要特點
即時伺服器啟動:Vite 透過原生 ES 模組提供文件,允許開發伺服器幾乎立即啟動,即使對於大型專案也是如此。
快速熱模組替換(HMR):Vite 的 HMR 非常快,可以在您開發時近乎即時地更新您的 React 元件。
最佳化構建:Vite 使用 Rollup 進行生產構建,透過程式碼分割和樹搖動等功能確保高效捆綁。
現代 JavaScript 支援:Vite 內建了對最新 JavaScript 功能的支持,包括 TypeScript、JSX 和 Sass 等 CSS 預處理器。
Vite 與 Webpack
雖然 Webpack 多年來一直是流行的選擇,但它通常需要複雜的配置,並且由於其捆綁過程,在開發過程中可能會比較慢。相較之下,Vite 簡化了設定過程並在開發過程中跳過捆綁,從而縮短了伺服器啟動時間和 HMR。 Vite 的生產版本也經過高度優化,與 Webpack 非常相似,但配置更簡單。
為什麼將 Vite 與 React 結合使用?
速度:Vite 快速的伺服器啟動和 HMR 使開發 React 應用程式變得更容易,無需等待漫長的捆綁過程。
簡單:Vite 易於使用的設定讓您專注於建立 React 元件,而不是設定建置工具。
效率: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
關鍵文件和資料夾的詳細信息
index.html:此檔案是應用程式的入口點,位於根目錄中。與傳統的捆綁器不同,Vite 在開發過程中直接提供該 HTML 檔案。這是你的 React 應用程式安裝的地方,Vite 會注入必要的腳本來載入應用程式。
src/:src 資料夾包含您的所有應用程式程式碼。
main.jsx:這是 React 應用程式的主要入口點。它導入 React,渲染根元件 (App.jsx),並將其附加到 index.html 檔案中的 #root 元素。
App.jsx:這是應用程式的根元件,您將在其中開始建立 UI。隨著專案的成長,您可以修改此文件以添加更多元件。
vite.config.js:此檔案包含Vite的設定。它允許你自訂 Vite 的行為、添加插件或修改建置過程,但對於大多數小型項目,你可能不需要碰觸這個檔案。
關鍵文件
-
index.html :注入 React 應用程式的 HTML 檔案。它包含一個 id="root" 的元素將在其中安裝 React 應用程式。
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite React App</title> <div id="root"></div> <script type="module" src="/src/main.jsx"></script>
- 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></app> </react.strictmode> );
- src/App.jsx :React 應用程式的主要元件。您將在此處開始建立 UI。預設情況下,它包含一個簡單的 React 元件,但您可以對其進行修改以滿足您的需求。
import React from 'react'; function App() { return ( <div> <h1 id="Welcome-to-Vite-React">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 id="Simple-List-with-Vite-and-React">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="%7Blogo%7D" alt="App Logo"> <h1 id="Welcome-to-Vite-React-App">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 id="Welcome-to-Vite-React-App">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 id="Welcome-to-the-updated-Vite-React-App">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.
-
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
- 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.
-
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中文網其他相關文章!

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

簡單JavaScript函數用於檢查日期是否有效。 function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //測試 var

本文探討如何使用 jQuery 獲取和設置 DOM 元素的內邊距和外邊距值,特別是元素外邊距和內邊距的具體位置。雖然可以使用 CSS 設置元素的內邊距和外邊距,但獲取準確的值可能會比較棘手。 // 設定 $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); 你可能會認為這段代碼很

本文探討了十個特殊的jQuery選項卡和手風琴。 選項卡和手風琴之間的關鍵區別在於其內容面板的顯示和隱藏方式。讓我們深入研究這十個示例。 相關文章:10個jQuery選項卡插件

發現十個傑出的jQuery插件,以提升您的網站的活力和視覺吸引力!這個精選的收藏品提供了不同的功能,從圖像動畫到交互式畫廊。讓我們探索這些強大的工具:相關文章:1

HTTP-Console是一個節點模塊,可為您提供用於執行HTTP命令的命令行接口。不管您是否針對Web服務器,Web Serv

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

當div內容超出容器元素區域時,以下jQuery代碼片段可用於添加滾動條。 (無演示,請直接複製到Firebug中) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。