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与水合时的一定要对上哦

相关推荐
凯程序猿1号1 小时前
Web墨卡托EPSG3857瓦片行列号XYZ与经纬度双向换算及地面分辨率推导
前端·电脑
qq_274475151 小时前
第 21 篇:Proxy 代理与 Reflect:数据劫持基础,Vue 响应式底层原理前置
前端·javascript·vue.js
JudithHuang2 小时前
Angular 响应式表单:TS 建模型与校验规则
前端·javascript·angular·angular.js
拖孩2 小时前
群里有人开始比「次数」之后,我做了个排行榜小程序
前端·后端·微信小程序
陈随易2 小时前
CDN 自带安全防护,SQL 注入、XSS、命令攻击现原形
前端·后端
lgbisha3 小时前
银河麒麟入门:日志刷满终端,用 less 定位关键词并看前后几行
java·前端·less·银河麒麟
w-w0w-w4 小时前
CSRF 与 JWT 漏洞原理、攻击手法及防御机制
前端·网络·csrf
默 语4 小时前
HarmonyOS7 组件通用事件(一):四大事件总览——组件的生死、身位与存在感
服务器·前端·javascript
低代码布道师4 小时前
第06篇:用户新增——React Hook Form + Zod 搭建可复用的表单体系
前端·react.js·前端框架
前端的日常4 小时前
不花一分钱,每天白嫖 Cloudflare 的大模型接口,手把手教你接入
前端