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

建立生產就緒的 SSR React 應用程式

Jan 05, 2025 am 11:51 AM

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 />)
}
登入後複製
登入後複製

更新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 />
  </StrictMode>,
)
登入後複製
登入後複製

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

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

重新匯出主伺服器文件

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

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



<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 />)
}
登入後複製
登入後複製

運行應用程式

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

// ./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 />
  </StrictMode>,
)
登入後複製
登入後複製

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

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



<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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

熱門話題

Java教學
1655
14
CakePHP 教程
1413
52
Laravel 教程
1306
25
PHP教程
1252
29
C# 教程
1226
24
前端熱敏紙小票打印遇到亂碼問題怎麼辦? 前端熱敏紙小票打印遇到亂碼問題怎麼辦? Apr 04, 2025 pm 02:42 PM

前端熱敏紙小票打印的常見問題與解決方案在前端開發中,小票打印是一個常見的需求。然而,很多開發者在實...

神秘的JavaScript:它的作用以及為什麼重要 神秘的JavaScript:它的作用以及為什麼重要 Apr 09, 2025 am 12:07 AM

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

誰得到更多的Python或JavaScript? 誰得到更多的Python或JavaScript? Apr 04, 2025 am 12:09 AM

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

如何實現視差滾動和元素動畫效果,像資生堂官網那樣?
或者:
怎樣才能像資生堂官網一樣,實現頁面滾動伴隨的動畫效果? 如何實現視差滾動和元素動畫效果,像資生堂官網那樣? 或者: 怎樣才能像資生堂官網一樣,實現頁面滾動伴隨的動畫效果? Apr 04, 2025 pm 05:36 PM

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

JavaScript的演變:當前的趨勢和未來前景 JavaScript的演變:當前的趨勢和未來前景 Apr 10, 2025 am 09:33 AM

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

如何使用JavaScript將具有相同ID的數組元素合併到一個對像中? 如何使用JavaScript將具有相同ID的數組元素合併到一個對像中? Apr 04, 2025 pm 05:09 PM

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

JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

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

前端開發中如何實現類似 VSCode 的面板拖拽調整功能? 前端開發中如何實現類似 VSCode 的面板拖拽調整功能? Apr 04, 2025 pm 02:06 PM

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

See all articles