使用 Vite 和 React.js 進行伺服器端渲染 (SSR) 指南
讓我們更深入地了解伺服器端渲染 (SSR) 的概念以及它如何增強 Web 應用程式的使用者體驗。
伺服器端渲染的概念
當使用者造訪您的網站時,他們通常最初會收到裸 HTML,然後觸發載入其他資源,例如 JavaScript(例如 App.js)和 CSS(例如 style.css)。這種傳統方法通常稱為客戶端渲染,這意味著使用者必須等待這些資源下載並執行才能看到任何有意義的內容。這種延遲可能會導致用戶體驗不佳,尤其是對於連接速度或裝置較慢的用戶而言。
伺服器端渲染透過向使用者發送完全渲染的 HTML 頁面來回應其初始請求來解決此問題。此預先渲染的 HTML 包含完整的標記,可讓使用者立即查看內容,而無需等待 JavaScript 載入和執行。
SSR 的主要優點包括:
減少最大內容繪製 (LCP) 的時間:使用者可以更快地看到內容,因為伺服器發送完整的 HTML 文件。
改進的 SEO:搜尋引擎可以更有效地索引您的內容,因為內容可以輕鬆以 HTML 格式取得。
更好的初始使用者體驗:使用者可以更快地開始閱讀內容並與內容互動,從而提高參與率。
平衡績效指標
雖然 SSR 可以減少 LCP,但它可能會增加 與下一次繪製的交互作用 (INP) 的時間。這是頁面載入後使用者與頁面互動所需的時間。目標是確保當用戶決定與網站互動時(例如單擊按鈕),必要的 JavaScript 已在後台加載,從而使互動流暢且無縫。
SSR 的糟糕實作可能會導致使用者看到內容但無法與其交互,因為 JavaScript 尚未載入。這可能比等待整個頁面最初加載更令人沮喪。因此,持續監控和測量效能指標以確保 SSR 真正改善使用者體驗至關重要。
在 Vite 和 React.js 中設定 SSR
我們會將其分解為幾個步驟:
- 建立 ClientApp 元件
- 更新index.html
- 建立 ServerApp 元件
- 設定建置腳本
- 設定節點伺服器
1. 建立ClientApp組件
我們首先建立一個 ClientApp.jsx 文件,它將處理所有特定於瀏覽器的功能。
// ClientApp.jsx import { hydrateRoot } from 'react-dom/client'; import { BrowserRouter } from 'react-router-dom'; import App from './App';
在這裡,我們從react-dom/client 導入HydraRoot,從react-router-dom 導入BrowserRouter,以及我們的主要App 元件。
// ClientApp.jsx // Hydrate the root element with our app hydrateRoot(document.getElementById('root'), <BrowserRouter> <App /> </BrowserRouter> );
我們使用 HydroRoot 在客戶端渲染我們的應用程序,指定根元素並使用 BrowserRouter 包裝我們的應用程式。此設定可確保所有特定於瀏覽器的程式碼都保留在此處。
接下來,我們需要修改我們的App.jsx。
// App.jsx import React from 'react'; // Exporting the App component export default function App() { return ( <div> <h1>Welcome to My SSR React App!</h1> </div> ); }
在這裡,為了演示目的,我們保持應用程式元件簡單。我們將其匯出,以便它可以在客戶端和伺服器環境中使用。
2.更新index.html
接下來,我們需要更新index.html以載入ClientApp.jsx而不是App.jsx,並添加解析令牌以拆分伺服器中的HTML文件,以便我們可以串流傳輸根div中的內容。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="./vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React + TS</title> </head> <body> <div id="root"><!--not rendered--></div> <script type="module" src="./src/ClientApp.jsx"></script> </body> </html>
3. 建立ServerApp元件
現在,讓我們建立一個 ServerApp.jsx 檔案來處理伺服器端渲染邏輯。
// ServerApp.jsx import { renderToPipeableStream } from 'react-dom/server'; import { StaticRouter } from 'react-router-dom/server'; import App from './App'; // Export a function to render the app export default function render(url, opts) { // Create a stream for server-side rendering const stream = renderToPipeableStream( <StaticRouter location={url}> <App /> </StaticRouter>, opts ); return stream; }
4. 設定建置腳本
我們需要更新 package.json 中的建置腳本來建置客戶端和伺服器套件。
{ "scripts": { "build:client": "tsc vite build --outDir ../dist/client", "build:server": "tsc vite build --outDir ../dist/server --ssr ServerApp.jsx", "build": "npm run build:client && npm run build:server", "start": "node server.js" }, "type": "module" }
在這裡,我們為客戶端和伺服器定義單獨的建置腳本。 build:client 腳本建立用戶端捆綁包,而 build:server 腳本使用 ServerApp.jsx 建置伺服器套件。建置腳本運行兩個建置步驟,啟動腳本使用 server.js(將在下一步中建立)運行伺服器。
∴ 如果您不使用 TypeScript,請從客戶端和伺服器版本中刪除 tsc。
5. 配置節點伺服器
最後,讓我們在 server.js 中設定我們的 Node 伺服器。
// server.js import express from 'express'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import renderApp from './dist/server/ServerApp.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const PORT = process.env.PORT || 3001; // Read the built HTML file const html = fs.readFileSync(path.resolve(__dirname, './dist/client/index.html')).toString(); const [head, tail] = html.split('<!--not rendered-->'); const app = express(); // Serve static assets app.use('/assets', express.static(path.resolve(__dirname, './dist/client/assets'))); // Handle all other routes with server-side rendering app.use((req, res) => { res.write(head); const stream = renderApp(req.url, { onShellReady() { stream.pipe(res); }, onShellError(err) { console.error(err); res.status(500).send('Internal Server Error'); }, onAllReady() { res.write(tail); res.end(); }, onError(err) { console.error(err); } }); }); app.listen(PORT, () => { console.log(`Listening on http://localhost:${PORT}`); });
In this file, we set up an Express server to handle static assets and server-side rendering. We read the built index.html file and split it into head and tail parts. When a request is made, we immediately send the head part, then pipe the stream from renderApp to the response, and finally send the tail part once the stream is complete.
By following these steps, we enable server-side rendering in our React application, providing a faster and more responsive user experience. The client receives a fully rendered page initially, and the JavaScript loads in the background, making the app interactive.
Conclusion
By implementing server-side rendering (SSR) in our React application, we can significantly improve the initial load time and provide a better user experience. The steps involved include creating separate components for client and server rendering, updating our build scripts, and configuring an Express server to handle SSR. This setup ensures that users receive a fully rendered HTML page on the first request, while JavaScript loads in the background, making the application interactive seamlessly. This approach not only enhances the perceived performance but also provides a robust foundation for building performant and scalable React applications.
以上是使用 Vite 和 React.js 進行伺服器端渲染 (SSR) 指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python和JavaScript開發者的薪資沒有絕對的高低,具體取決於技能和行業需求。 1.Python在數據科學和機器學習領域可能薪資更高。 2.JavaScript在前端和全棧開發中需求大,薪資也可觀。 3.影響因素包括經驗、地理位置、公司規模和特定技能。

實現視差滾動和元素動畫效果的探討本文將探討如何實現類似資生堂官網(https://www.shiseido.co.jp/sb/wonderland/)中�...

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

如何在JavaScript中將具有相同ID的數組元素合併到一個對像中?在處理數據時,我們常常會遇到需要將具有相同ID�...

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

探索前端中類似VSCode的面板拖拽調整功能的實現在前端開發中,如何實現類似於VSCode...
