Rich woman to report, today want to problem can not come out, with a hair, did not expect ah did not expect, my thick (MEI) dense (sheng) MAO (JI) sheng (gen) hair and a few roots, must get rid of this can not think of a problem on the bad habit of pulling hair. What strange habits do you have when you have a problem?

Imagine a young beautiful girl her hair into the image of SAN MAO (science: women bald probability is very low will not become a British royal prince William handed down, poor new born prince harry, the son of the world and more than a bald man), bald do, only have to study hard to make money, and then use the money to go hair transplant hair… Cycle…

React Server render

Those of you who have written the React component know that the React component is usually rendered in javascript on the browser side. The Dom structure generated by it is generated by JS calculation in the later stage. In the following figure, we can see that the DOM structure in the page source file with id root is actually empty. But in the element, you can already see the Dom tree being generated.

Client renders DOM structure diagram

The server renders the DOM structure diagram

Why use server-side rendering

With a brief overview of React-SSR, the main purpose of using server-side rendering is to solve the following problems:

1. Search engine Optimization (SEO)

Because the React component uses JS to render in the browser, the data that the actual search engine crawls is the data without DOM structure shown in Figure 1. , and extremely unfriendly, as shown in Figure 1.

2. It can solve the problem of the first blank screen

Components rendered by Js require performance, so the browser side takes a long time to render components on poor performance terminals. When a browser executes a JS rendering component, it is called a white screen to the user.

Before enabling server rendering

After server rendering is enabled

Script calculation time comparison before and after enabling

If your project has these problems and you don’t want to ditch the React component, try using React server rendering. Server rendering, what exactly does it use?

Server side rendering principles

There are many server-side rendering methods, and the dominant server-side language is nodeJS rendering. The following is a simple schematic diagram:

Server side render simple flowchart

In a nutshell, there are three steps:

1. The client initiates a request

The Nodejs server analyzes the data structure of the page and renders the React component

3. The client displays HTML

Example explanation

Let’s take a look at the Express React server rendering example. Express provides the page and mid-tier API(click TAB to switch the interface to call) services, while Webpack implements the server and client React component packaging.

Interface to preview

It consists of one page and two components. Components 1 and 2 can both return the first screen data and re-perform the React component rendering on the client.

First-screen DOM structure

Instance address :(this is an express_react_ssr scaffold) github.com/webqdtalk/e…

Runtime environment

Nodejs:6.9.0 not limited to this version Webpack: 3.5.2 Not limited to this version package. json and related instructionsCopy the code

This is a Package. Json:

{
  "name": "react-express-ssr"."version": "0.0.0"."private": true."scripts": {
    "start": "webpack --progress && node ./bin/www"
  },
  "dependencies": {
    "axios": "^ 0.18.0." "// Implement ajax requests in the component"babel-core": "^ 6.24.0"// Package the React component"babel-loader": "^ 6.4.1." "// Package the React component"babel-preset-es2015": "^ 6.24.0"// Package the React component"babel-preset-react": "^ 6.23.0"// Package the React component"cookie-parser": "~ 1.4.3", / / express dependencies"css-loader": "^ 0.23.1", / / express dependencies"debug": "~ 2.6.9." ", / / express dependencies"ejs": "~ 2.5.7." ", / / express dependencies"express": "~ 4.16.0", / / express dependencies"extract-text-webpack-plugin": "^ 2.1.0." ",// Package SCSS file dependencies"http-errors": "~ 1.6.2", / / express dependencies"morgan": "~ 1.9.0", / / express dependencies"node-sass": "^ 4.5.1." ", // Package SCSS file dependencies"react": "^ 16.8.6"// Package the React component"react-dom": "^ 16.8.6"// Pack the react component,"sass-loader": "^ 6.0.3",// Package SCSS file dependencies"style-loader": "^ 0.13.0",// Package SCSS file dependencies"webpack": "^ 3.5.2." "// Pack the react component},"devDependencies": {
    "babel-preset-env": "^ 1.7.0"."babel-register": "^ 6.26.0"}}Copy the code

After the Clone project, execute NPM I directly in the root directory

After installation, run NPM start and open the browser to localhost:3000.

Key Module Description Portal file configuration After NPM start is executed and localhost:3000 is accessed, server/index.js is imported into the express portal file app.js

App.js

How is server routing implemented

Express provides the router method

router.get('/urlpath'.function(req, res, next) { const html=ReactDOMServer.renderToStaticMarkup(<App />); Res. Render (pageejs, {title:"Server render",content: html });
});
Copy the code

How to implement server-side rendering

Webpack entry file: Server/index, introduces the components of the components in the js, and perform ReactDOMServer. RenderToStaticMarkup method, the component for the page on the server side rendering DOM string structure, service is provided by express page again, Output in ejS templates.

The two apis in Figure 4 are used to request data when clicking TAB. Figure 5 shows the EJS template file.

Server/index.js

Views/index.ejs

How do servers and clients package components? The Webpack configuration is as follows:

Webpack.config.js

The client rendering entry file is /components/app.js, which also contains the server side entry file to ensure that the server side and the client side use the same set of component output, and also ensure that the client side components can continue to operate normally after the server side rendering is finished.

Components/app.js

As you can see in the image below, this entry file references two additional components: swichTab and ssrPlugin, which are basically the same as the react component.

Components/index.js

Attention points of the practice process

1. Express cannot execute import, resulting in an error.

NPM I babel-register –save simultaneously configure babel-register in bin/ WWW

require('babel-register')({
  presets: ['env']});Copy the code

2. The server displays an error when rendering the CSS or SCSS file

Solution: Since the server directly runs CSS or SCSS files, syntax errors may occur. Therefore, in actual components, require SCSS files need to be fault-tolerant or dynamically loaded on demand.

try{
    require('./index.scss'}catch(e){console.log(e.message);}catch(e){console.log(e.message);}catch(e){console.log(e.message); }Copy the code

Although the server rendering is good, the impact on the transformation of the project is still relatively large, and the transformation needs to be carefully evaluated

You get it!!

If the article is wrong, welcome to be corrected!!

Welcome to my public account, bald together, hair transplant together

Web front-end Talk