React Server API + Vite 简单实现SSR【根据文档提供的案例进行分析】

文档:cn.vite.dev/guide/ssr.h...

版本:react 19。 vite 5.4.19 (vite 7中一些api行为不太一样)

关键步骤:

第一步:server返回html

  1. 一个server.js -- 使用类似模板语法,替换index.html里一些特定"模板"为React组件,组合成html dom
js 复制代码
import {createServer} from 'vite';
import express from 'express';
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'

import path from 'node:path'

const __dirname = path.dirname(fileURLToPath(import.meta.url))


const vite = await createServer({
   server:{middlewareMode:true},
   appType:'custom'
})


const app = express()


app.use(vite.middlewares)

app.use("*all", async (req,res)=>{
   const template= await vite.transformIndexHtml(
       req.url,
       await fs.readFileSync(
       path.resolve(__dirname, 'index.html'),
       'utf-8',
       )    
   )
   
   const  {getMyRender} = await vite.ssrLoadModule(path.resolve(__dirname, 'server-entry.jsx'))  
   //注意这里,vite7 不是这么用的,它需要.render;vite 5 vite.ssrLoadModule返回{ getMyRender: [Getter], [Symbol(Symbol.toStringTag)]: 'Module' }
   

   const appHTML = await getMyRender(req.url)
   //注意这里,vite7返回一个html对象,可以appHTMl.html ;vite 5这里就一个html字符串
   
   const html = template
   .replace(`<!--app-->`,()=>appHTML)//替换index.html里的模板为React渲染好的组件
   //vite7的官方案例里给的可以分别替换head 和html body
   res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
})


app.listen(3000,()=>{
   console.log('server running on 3000')
})
  1. 一个server-entry.js -- 调用React.renderToString(<StrictMode><你的组件></StrictMode>)返回html字符串,server.js里可以使用这个字符串来替换index.html里的"模板"
jsx 复制代码
import { renderToString } from "react-dom/server"
import {App} from "./App"
import React, { StrictMode } from 'react'


export function getMyRender(){
  const htmlstr= renderToString(<StrictMode><App/></StrictMode>)
  return htmlstr
}
  1. 一个index.html - <!--app-->会被server.js替换成React组件,是渲染好的DOM,不是jsx。
html 复制代码
<!doctype html>
<html lang="en">
 <head>
   <meta charset="UTF-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />
   <title>Vite + React</title>
 </head>
 <body><div id="app"><!--app--></div>
   <script type="module" src="./client-entry.jsx"></script>
 </body>
</html>

===

第二步: hydrate

关注一下index.html的 <script type="module" ...> 它引用了一个client-entry.jsx,这里就是水合发生的地方 1.准备client-entry. index.html里要注意挂载点<div id='app'>要在那

jsx 复制代码
import  { StrictMode } from "react"
import { hydrateRoot } from "react-dom/client"
import {App} from "./App"


hydrateRoot(document.getElementById("app"),<StrictMode><App/></StrictMode>)

第三步 node server.js 运行即可

可能的报错

Hydration failed because the server rendered HTML didn't match the client.

debug:先不加水合(就是把index.html里的script先注释掉)看看渲染结果是不是正常,有可能vite版本会带来ssrLoadModule返回类型的细微差异,导致server拼的html不对,那水合时自然找不到对应的dom元素了,就会报错。server返回的dom与水合时的一定要对上哦

相关推荐
Fly2 小时前
我来提需求,你带着 Codex 做项目:AI 全栈课程开始实战了
前端
集智飞行3 小时前
解决mavros2 ros2版本cpu占用高的问题
java·服务器·前端
HSunR4 小时前
ruoyi 若依 自定义注解 参数校验
java·前端·数据库
拆房老料5 小时前
ONLYOFFICE也能像Microsoft Word和WPS一样分别设置中西文字体
前端·html·word·开源软件·wps
Solis程序员5 小时前
Stripe 幂等表:把「不确定的重试」变成「查表返回」
前端·安全·bootstrap·php·agent
李纲明5 小时前
WordPress 站点变慢:按 TTFB → 缓存 → 查询 → 前端 分层排查(含配置注意)
前端·缓存·性能优化·wordpress·后端开发
程序人生8885 小时前
PDF 转 Word 版式错乱、表格丢失?DocConverter Web 格式互转引擎的保真实践
前端·人工智能·opencv·机器学习·pdf·word
粥里有勺糖6 小时前
安利一下最近用的桌面“Agent” | T3 Code
前端·github·ai编程
xy34536 小时前
Axure 9.0 动态面板基本操作
前端·ui·html·axure·原型·产品设计
不停喝水7 小时前
【前端转全栈java速通课】 项目实战④7-11节 操作数据库-登录-注册-修改密码-注销-mubatis-plus简化crud-
java·前端·数据库