Why do you have server-side rendering?

Framework development is a hot trend at present, and SPA mode is recognized by more and more people. However, with the deepening of research, some problems are gradually highlighted.

The most important two points, one is the home page needs to wait; Second, it’s not good for SEO.

In order to solve these problems, the framework has launched its own solution — Server Side Rendering.

How to implement a SIMPLE sequence repeat (SSR) manually in React?

The first step to real ammunition

First, create a folder SRC under your project and place three folders client (client code), common (common code), and Server (server code) inside.

Here the Server folder is the focus of our attention. In this server folder, we need to create an HTTP.js file with the following content to start a service.

//http.js
const express = require("express")
const app = express()
app.listen(3000,function(){console.log("server is runing")})
export default app;
Copy the code

Add another index.js file with the following contents. The purpose of splitting the two files is to keep the service code separate from the business code.

Import app from "./ HTTP "import React from" React "import {renderToString} from "react-dom/server" // Convert components to string format import Home from ".. /common/Home" app.get("/",function(req,res){const string = renderToString(<Home></Home>) // res.send(' // this is a string template <html> <head> <title>react-ssr</title> </head> <body> <div id="root">${string}</div> </body> </html> `) })Copy the code

Here are a few points:

  • RenderToString is a method that converts components to string format.

  • Home is a component created under the common folder and contains the following contents:

    import React from “react” function Home(){ return (

    hello world

    ) } export default Home;

Note:

If we use Node directly to start the service, we will get a syntax error.

  • ESModule syntax is not supported under Node

  • Node does not support the JSX syntax in React

So we need to introduce webPack for packaging and then start the service.

# Webpack configuration

We create a webpack.server.js under our project with the following contents:

const path = require("path")
module.exports = {
    mode:"none",
    target:"node",
    entry:"./src/server/index.js",
    output:{
        path:path.join(__dirname,"dist"),
        filename:"build.js"
    },
    module:{
        rules:[
            {
                test:/\.js$/,
                exclude:/node_modules/,
                use:{
                    loader:"babel-loader",
                    options:{
                        presets:['@babel/preset-env','@babel/preset-react']
                    }
                }
            }
        ]
    }
}
Copy the code

Note that we need to install Webpack webpack-CLI.

For the JS file, we need to use babel-loader and hand it over to Babel, so download it

Babel-loader @babel/ core@babel /preset-env @babel/preset-react.

Next configure options and add preset presets.

# Webpack packaging

Once the configuration file is complete, we need to pack it. The packing instruction is NPX webpack — config webpack.server.js. Json, we need to configure a handy directive for our own use. Modify it as follows:

/ / package. Json {" name ":" the react - SSR ", "version" : "1.0.0", "description" : ""," main ":". The main js ", "scripts" : { "dev:server-build":"npx webpack --config webpack.server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies" : {" @ Babel/core ":" ^ 7.12.9 ", "@ Babel/preset - env" : "^ 7.12.7", "@ Babel/preset - react" : "^ 7.12.7", "Babel - loader" : "^ 8.2.2", "express" : "^ 4.17.1", "react" : "^ 17.0.1", "the react - dom" : "^ 17.0.1", "webpack" : "^5.9.0", "webpack-cli": "^4.2.0"}}Copy the code

When NPM run Dev is packaged, a dist folder appears with a build.js file in it.

Node Start service

Finally, we can launch the file directly on the terminal using Node dist/build.js. Entering the corresponding URL in the web page will display a server rendering example that we implemented manually, but this page is a purely static page.

At this point, implementing a React SSR is complete