首頁  >  文章  >  web前端  >  使用 Vite 和 React.js 進行伺服器端渲染 (SSR) 指南

使用 Vite 和 React.js 進行伺服器端渲染 (SSR) 指南

王林
王林原創
2024-08-06 02:35:32765瀏覽

A Guide to Server-Side Rendering (SSR) with Vite and React.js

讓我們更深入地了解伺服器端渲染 (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

我們會將其分解為幾個步驟:

  1. 建立 ClientApp 元件
  2. 更新index.html
  3. 建立 ServerApp 元件
  4. 設定建置腳本
  5. 設定節點伺服器

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

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