react服务端渲染

153 阅读1分钟

react服务端渲染

const express = require('express');
const ReactDomServer = require('react-dom/server');
const ServerApp = require('../../bundle/server-app.js').default;
const fs = require('fs');
const path = require('path');

const app = express();
const serverString = ReactDomServer.renderToString(ServerApp);
const text = fs.readFileSync(
  path.join(__dirname, '../../bundle/index.html'),
  'utf-8'
);
const htmltext = text.replace('<!--1314-->', serverString);
console.log(text);
app.use(express.static(path.join(__dirname, '../../bundle')));
app.get('/', (req, res) => {
  res.send(htmltext);
});
app.listen(5001, () => {
  console.log('服务端启动了');
});
  • 使用renderToString服务端渲染函数将客户端组件进行转化
  • 使用fs读取编译之后的html文件,这个html会引入对应的已经打包好的客户端的js,然后使用replace将renderToString返回的结果插入到对应的html中
  • 然后理由express路由响应参数res返回对应的html进行渲染。