搜尋
首頁web前端js教程建立生產就緒的 SSR React 應用程式

Building Production-Ready SSR React Applications

在每一毫秒都至關重要的世界裡,伺服器端渲染已成為前端應用程式的基本功能。

本指南將引導您了解使用 React 建立可用於生產的 SSR 的基本模式。您將了解具有內建 SSR(例如 Next.js)的基於 React 的框架背後的原理,並學習如何創建自己的自訂解決方案。

提供的程式碼是生產就緒的,具有客戶端和伺服器部分的完整建置流程,包括 Dockerfile。在此實作中,Vite 用於建立用戶端和 SSR 程式碼,但您可以使用您選擇的任何其他工具。 Vite也為客戶端提供了開發模式下的熱重載。

如果您對此設定的無 Vite 版本感興趣,請隨時與我們聯繫。

目錄

  • 什麼是SSR
  • 創建應用程式
    • 初始化 Vite
    • 更新 React 元件
    • 建立伺服器
    • 配置建置
  • 路由
  • 碼頭工人
  • 結論

什麼是SSR

伺服器端渲染 (SSR) 是 Web 開發中的一種技術,伺服器在將網頁傳送到瀏覽器之前產生網頁的 HTML 內容。與傳統的用戶端渲染 (CSR) 不同,JavaScript 在載入空白 HTML shell 後在使用者裝置上建立內容,SSR 直接從伺服器提供完全渲染的 HTML。

SSR 的主要優點:

  • 改進的 SEO:由於搜尋引擎爬蟲接收完全渲染的內容,SSR 可確保更好的索引和 排名。
  • 更快的首次繪製:使用者幾乎立即看到有意義的內容,因為伺服器處理了繁重的工作 渲染。
  • 增強效能:透過減少瀏覽器上的渲染工作量,SSR 為 使用較舊或功能較弱的設備的使用者。
  • 無縫伺服器到客戶端資料傳輸:SSR 可讓您將動態伺服器端資料傳遞到客戶端,而無需 重建客戶端包。

創建應用程式

使用 SSR 的應用程式流程遵循以下步驟:

  1. 閱讀範本 HTML 檔案。
  2. 初始化 React 並產生應用內容的 HTML 字串。
  3. 將產生的 HTML 字串插入範本中。
  4. 將完整的 HTML 傳送到瀏覽器。
  5. 在客戶端,匹配 HTML 標籤並水合應用程序,使其具有互動性。

初始化Vite

我更喜歡使用pnpm和react-swc-ts Vite模板,但你可以選擇任何其他設定。

pnpm create vite react-ssr-app --template react-swc-ts

安裝依賴項:

pnpm create vite react-ssr-app --template react-swc-ts

更新 React 元件

在典型的 React 應用程式中,index.html 有一個 main.tsx 入口點。使用 SSR,您需要兩個入口點:一個用於伺服器,一個用於客戶端。

伺服器入口點

Node.js 伺服器將運行您的應用程式並透過將 React 元件渲染為字串 (renderToString) 來產生 HTML。

pnpm install

客戶端入口點

瀏覽器將水合伺服器產生的 HTML,將其與 JavaScript 連接以使頁面具有互動性。

Hydration 是將事件偵聽器和其他動態行為附加到伺服器呈現的靜態 HTML 的過程。

// ./src/entry-server.tsx
import { renderToString } from 'react-dom/server'
import App from './App'

export function render() {
  return renderToString(<app></app>)
}

更新index.html

更新專案根目錄中的index.html 檔案。 ;佔位符是伺服器將注入產生的 HTML 的位置。

// ./src/entry-client.tsx
import { hydrateRoot } from 'react-dom/client'
import { StrictMode } from 'react'
import App from './App'

import './index.css'

hydrateRoot(
  document.getElementById('root')!,
  <strictmode>
    <app></app>
  </strictmode>,
)

伺服器所需的所有依賴項都應作為開發依賴項(devDependency)安裝,以確保它們不包含在客戶端捆綁包中。

接下來,在專案的根目錄中建立一個名為 ./server 的資料夾並新增以下檔案。

重新匯出主伺服器文件

重新匯出主伺服器檔案。這使得運行命令更加方便。


  
    <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>
  
  
    <div>



<h3>
  
  
  Create Server
</h3>

<p>First, install the dependencies:<br>
</p>

<pre class="brush:php;toolbar:false">pnpm install -D express compression sirv tsup vite-node nodemon @types/express @types/compression

定義常數

HTML_KEY常數必須與index.html中的佔位符註解相符。其他常量管理環境設定。

// ./server/index.ts
export * from './app'

創建 Express 伺服器

為開發和生產環境設定不同配置的 Express 伺服器。

// ./server/constants.ts
export const NODE_ENV = process.env.NODE_ENV || 'development'
export const APP_PORT = process.env.APP_PORT || 3000

export const PROD = NODE_ENV === 'production'
export const HTML_KEY = `<!--app-html-->`

開發模式配置

開發中,使用Vite的中間件處理請求,並透過熱重載動態轉換index.html檔案。伺服器將載入 React 應用程式並將其渲染為每個請求的 HTML。

// ./server/app.ts
import express from 'express'
import { PROD, APP_PORT } from './constants'
import { setupProd } from './prod'
import { setupDev } from './dev'

export async function createServer() {
  const app = express()

  if (PROD) {
    await setupProd(app)
  } else {
    await setupDev(app)
  }

  app.listen(APP_PORT, () => {
    console.log(`http://localhost:${APP_PORT}`)
  })
}

createServer()

生產模式配置

在生產中,使用壓縮來優化效能,使用 Sirv 來提供靜態文件,並使用預先建置的伺服器套件來渲染應用程式。

// ./server/dev.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import { HTML_KEY } from './constants'

const HTML_PATH = path.resolve(process.cwd(), 'index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx')

export async function setupDev(app: Application) {
  // Create a Vite development server in middleware mode
  const vite = await (
    await import('vite')
  ).createServer({
    root: process.cwd(),
    server: { middlewareMode: true },
    appType: 'custom',
  })

  // Use Vite middleware for serving files
  app.use(vite.middlewares)

  app.get('*', async (req, res, next) => {
    try {
      // Read and transform the HTML file
      let html = fs.readFileSync(HTML_PATH, 'utf-8')
      html = await vite.transformIndexHtml(req.originalUrl, html)

      // Load the entry-server.tsx module and render the app
      const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH)
      const appHtml = await render()

      // Replace the placeholder with the rendered HTML
      html = html.replace(HTML_KEY, appHtml)
      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      // Fix stack traces for Vite and handle errors
      vite.ssrFixStacktrace(e as Error)
      console.error((e as Error).stack)
      next(e)
    }
  })
}

配置建置

要遵循建立應用程式的最佳實踐,您應該排除所有不必要的套件並僅包含應用程式實際使用的套件。

更新Vite配置

更新您的 Vite 設定以最佳化建置流程並處理 SSR 依賴項:

// ./server/prod.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import compression from 'compression'
import sirv from 'sirv'
import { HTML_KEY } from './constants'

const CLIENT_PATH = path.resolve(process.cwd(), 'dist/client')
const HTML_PATH = path.resolve(process.cwd(), 'dist/client/index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'dist/ssr/entry-server.js')

export async function setupProd(app: Application) {
  // Use compression for responses
  app.use(compression())
  // Serve static files from the client build folder
  app.use(sirv(CLIENT_PATH, { extensions: [] }))

  app.get('*', async (_, res, next) => {
    try {
      // Read the pre-built HTML file
      let html = fs.readFileSync(HTML_PATH, 'utf-8')

      // Import the server-side render function and generate HTML
      const { render } = await import(ENTRY_SERVER_PATH)
      const appHtml = await render()

      // Replace the placeholder with the rendered HTML
      html = html.replace(HTML_KEY, appHtml)
      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      // Log errors and pass them to the error handler
      console.error((e as Error).stack)
      next(e)
    }
  })
}

更新 tsconfig.json

更新 tsconfig.json 以包含伺服器檔案並適當配置 TypeScript:

pnpm create vite react-ssr-app --template react-swc-ts

建立 tsup 配置

使用 TypeScript 捆綁器 tsup 來建立伺服器程式碼。 noExternal 選項指定要與伺服器捆綁的套件。 請務必包含您的伺服器所使用的任何其他軟體包。

pnpm install

新增建置腳本

// ./src/entry-server.tsx
import { renderToString } from 'react-dom/server'
import App from './App'

export function render() {
  return renderToString(<app></app>)
}

運行應用程式

開發:使用以下命令以熱重載啟動應用程式:

// ./src/entry-client.tsx
import { hydrateRoot } from 'react-dom/client'
import { StrictMode } from 'react'
import App from './App'

import './index.css'

hydrateRoot(
  document.getElementById('root')!,
  <strictmode>
    <app></app>
  </strictmode>,
)

生產:建立應用程式並啟動生產伺服器:


  
    <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>
  
  
    <div>



<h3>
  
  
  Create Server
</h3>

<p>First, install the dependencies:<br>
</p>

<pre class="brush:php;toolbar:false">pnpm install -D express compression sirv tsup vite-node nodemon @types/express @types/compression

要驗證 SSR 是否正常運作,請檢查伺服器的第一個網路請求。回應應包含應用程式的完全呈現的 HTML。

路由

要為您的應用程式新增不同的頁面,您需要正確配置路由並在客戶端和伺服器入口點處理它。

// ./server/index.ts
export * from './app'

新增客戶端路由

在客戶端入口點使用 BrowserRouter 包裝您的應用程式以啟用客戶端路由。

// ./server/constants.ts
export const NODE_ENV = process.env.NODE_ENV || 'development'
export const APP_PORT = process.env.APP_PORT || 3000

export const PROD = NODE_ENV === 'production'
export const HTML_KEY = `<!--app-html-->`

新增伺服器端路由

在伺服器入口點使用 StaticRouter 處理伺服器端路由。將 url 作為 prop 傳遞,以根據請求呈現正確的路線。

// ./server/app.ts
import express from 'express'
import { PROD, APP_PORT } from './constants'
import { setupProd } from './prod'
import { setupDev } from './dev'

export async function createServer() {
  const app = express()

  if (PROD) {
    await setupProd(app)
  } else {
    await setupDev(app)
  }

  app.listen(APP_PORT, () => {
    console.log(`http://localhost:${APP_PORT}`)
  })
}

createServer()

更新伺服器配置

更新您的開發和生產伺服器設置,以將請求 URL 傳遞給渲染函數:

// ./server/dev.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import { HTML_KEY } from './constants'

const HTML_PATH = path.resolve(process.cwd(), 'index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'src/entry-server.tsx')

export async function setupDev(app: Application) {
  // Create a Vite development server in middleware mode
  const vite = await (
    await import('vite')
  ).createServer({
    root: process.cwd(),
    server: { middlewareMode: true },
    appType: 'custom',
  })

  // Use Vite middleware for serving files
  app.use(vite.middlewares)

  app.get('*', async (req, res, next) => {
    try {
      // Read and transform the HTML file
      let html = fs.readFileSync(HTML_PATH, 'utf-8')
      html = await vite.transformIndexHtml(req.originalUrl, html)

      // Load the entry-server.tsx module and render the app
      const { render } = await vite.ssrLoadModule(ENTRY_SERVER_PATH)
      const appHtml = await render()

      // Replace the placeholder with the rendered HTML
      html = html.replace(HTML_KEY, appHtml)
      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      // Fix stack traces for Vite and handle errors
      vite.ssrFixStacktrace(e as Error)
      console.error((e as Error).stack)
      next(e)
    }
  })
}

透過這些更改,您現在可以在 React 應用程式中建立與 SSR 完全相容的路由。然而,這種基本方法不處理延遲載入的元件(React.lazy)。有關管理延遲載入的模組,請參閱我的另一篇文章,使用串流和動態資料的高級 React SSR 技術,連結在底部。

碼頭工人

這是一個用於容器化您的應用程式的 Dockerfile:

// ./server/prod.ts
import { Application } from 'express'
import fs from 'fs'
import path from 'path'
import compression from 'compression'
import sirv from 'sirv'
import { HTML_KEY } from './constants'

const CLIENT_PATH = path.resolve(process.cwd(), 'dist/client')
const HTML_PATH = path.resolve(process.cwd(), 'dist/client/index.html')
const ENTRY_SERVER_PATH = path.resolve(process.cwd(), 'dist/ssr/entry-server.js')

export async function setupProd(app: Application) {
  // Use compression for responses
  app.use(compression())
  // Serve static files from the client build folder
  app.use(sirv(CLIENT_PATH, { extensions: [] }))

  app.get('*', async (_, res, next) => {
    try {
      // Read the pre-built HTML file
      let html = fs.readFileSync(HTML_PATH, 'utf-8')

      // Import the server-side render function and generate HTML
      const { render } = await import(ENTRY_SERVER_PATH)
      const appHtml = await render()

      // Replace the placeholder with the rendered HTML
      html = html.replace(HTML_KEY, appHtml)
      res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
    } catch (e) {
      // Log errors and pass them to the error handler
      console.error((e as Error).stack)
      next(e)
    }
  })
}

建置並執行 Docker 映像

// ./vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import { dependencies } from './package.json'

export default defineConfig(({ mode }) => ({
  plugins: [react()],
  ssr: {
    noExternal: mode === 'production' ? Object.keys(dependencies) : undefined,
  },
}))
{
  "include": [
    "src",
    "server",
    "vite.config.ts"
  ]
}

結論

在本指南中,我們為使用 React 建立生產就緒的 SSR 應用程式奠定了堅實的基礎。您已經學習如何設定專案、設定路由和建立 Dockerfile。此設定非常適合高效建立登陸頁面或小型應用程式。

探索程式碼

  • 範例:react-ssr-basics-example
  • 模板:react-ssr-template
  • Vite 額外範本: template-ssr-react-ts

相關文章

這是我的 React SSR 系列的一部分。更多文章敬請期待!

  • 建立生產就緒的 SSR React 應用程式(您在這裡)
  • 使用串流和動態資料的進階 React SSR 技術(即將推出)
  • 在 SSR React 應用程式中設定主題(即將推出)

保持聯繫

我總是樂於接受回饋、合作或討論技術想法 - 請隨時與我們聯繫!

  • 投資組合:maxh1t.xyz
  • 電子郵件:m4xh17@gmail.com

以上是建立生產就緒的 SSR React 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

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

jQuery檢查日期是否有效jQuery檢查日期是否有效Mar 01, 2025 am 08:51 AM

簡單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獲取元素填充/保證金jQuery獲取元素填充/保證金Mar 01, 2025 am 08:53 AM

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

10個jQuery手風琴選項卡10個jQuery手風琴選項卡Mar 01, 2025 am 01:34 AM

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

10值得檢查jQuery插件10值得檢查jQuery插件Mar 01, 2025 am 01:29 AM

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

HTTP與節點和HTTP-Console調試HTTP與節點和HTTP-Console調試Mar 01, 2025 am 01:37 AM

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

自定義Google搜索API設置教程自定義Google搜索API設置教程Mar 04, 2025 am 01:06 AM

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

jQuery添加捲軸到DivjQuery添加捲軸到DivMar 01, 2025 am 01:30 AM

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

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

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

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

DVWA

DVWA

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