SSR brief set up

Let us see briefly how to set up a simple React JS website with server-side rendering using Express.js. The configuration steps are along the following lines:

  1. Create a new folder for the React app.
  2. Install the dependencies like Babel.
  3. Configure the dependencies installed and set up the packages used by the server.
  4. Move all the code to the client directory and create a server directory.
  5. Create basic server code with express.
  6. Transpile all the code
  7. Test the server code.
  8. Configure webpack or any module bundler.
  9. Build the code.
  10. Test and debug.

schema

express + react 搭建基本的 ssr 服务

react 基于 ssr 的 api

ReactDomServer

renderToString() vs renderToStaticMarkup() 可以返回一个 react 节点的 html 但是 renderToStaticMarkup 返回的原始 html 没有 data-reactroot 这样的标签

import express from "express";
import React from "react";

import { renderToString } from "react-dom/server";
var router = express.Router();

const Home = ({ msg }) => {
  return msg;
};
/* GET home page. */
router.get("/home", (req, res, next) => {
  const html = renderToString(<Home msg={"hello"} />);
  res.send(html);
});
css 的引入

对于下面这样引入的css代码,es module 是并不能支持的

import './style.css'

import style from './style.module.css'

Last Updated: