//client/index.js import React from 'react' import ReactDom from 'react-dom' import Home from '../containers/Home'; ReactDom.hydrate( <Home/>, document.getElementById("root") )
//server/index.js
const express = require('express');
const app = express(); import React from 'react'; import { renderToString } from 'react-dom/server'
import Home from '../containers/Home' app.use(express.static('public')); var home = renderToString(<Home />); app.get("/",(req,res)=>{ res.send(`<html> <head> <title>服務端渲染</title> </head> <body> <div id="root">${home}</div> </body> <script src="./index.js"></script> </html>`) }) app.listen('3000',()=>{ console.log("服務器已經啓動"); })
拼接結果以下:html
項目地址:git@github.com:longlongdan/Reactssr.gitreact