Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of react Server rendering

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article shares with you the content of a sample analysis of react server rendering. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Preface

This article is an introductory tutorial based on react ssr, and more configuration and optimization are needed in the actual project, which is more suitable for friends who try react ssr for the first time. The technology involves koa2 + react, and the case is created using create-react-app

SSR introduction

Server Slide Rendering, abbreviated as ssr, that is, server-side rendering. This starts with SEO. The current react single-page application HTML code is as follows

React App You need to enable JavaScript to run this app.

If the main.js loads slowly, the white screen will flash.

Because the traditional search engine crawler can not crawl the content generated by JS, when it comes across a single-page web project, there is nothing to crawl. Will suffer a lot of losses on SEO, it is difficult to rank search engines to the front.

React SSR (react server rendering) just solves these two problems.

React SSR introduction

Here is an example to take you into the pit! First create a react project using create-react-app. Because we want to modify webpack, here we use react-app-rewired to start the project. The root directory creates a server directory to hold the server-side code, which we use here with koa2. The directory structure is as follows:

Let's take a look at how react ssr works.

This business flow chart is relatively clear. The server only generates HTML code. In fact, the front end will generate a copy of main.js for the server's HTML to use. This is how react ssr works. With this picture will be better understood, if the business is not understood clearly, the later estimate is very difficult to understand.

The SSR method provided by react has two renderToString and renderToStaticMarkup, and the difference is as follows:

The renderToString method is rendered with the data-reactid attribute. When the browser visits the page, main.js can recognize the contents of the HTML and will not execute React.createElement to create the DOM again.

RenderToStaticMarkup has no data-reactid attribute, and the page looks cleaner. When the browser visits the page, main.js does not recognize the HTML content and executes the React.createElement method in main.js to recreate the DOM.

Realization process

All right, now that we know how it works, we can start coding. The directory structure is as follows:

I haven't touched the demo of create-react-app. I just use this as a case. The front-end project is basically unchanged. We'll use this module on the server side later. The code is as follows:

Render () {return (

logo

Edit src/App.js and save to reload.

Learn React);}} export default App

Create a new server directory in the project to store the server code. To simplify, I only have 2 files here, the ES6 we use in the project, so we need to configure. Babelrc

.babelrc configuration Because to use ES6 {"presets": ["env", "react"], "plugins": ["transform-decorators-legacy", "transform-runtime", "react-hot-loader/babel", "add-module-exports", "transform-object-rest-spread", "transform-class-properties", ["import", {"libraryName": "antd" "style": true}]]} index.js project entry to do some preprocessing Use asset-require-hook to filter out something like import logo from ". / logo.svg" Such a resource code. Because our server only needs pure HTML code, if we don't filter it out, we will report an error. For name here, we remove the require ("asset-require-hook") of the hash value ({extensions: ["svg", "css", "less", "jpg", "png", "gif"], name:'/ static/media/ [name]. [ext]'}); require ("babel-core/register") (); require ("babel-polyfill"); require (". / app") The public/index.html html template code needs to be adjusted. {{root}} this can be any string that can be replaced, and the server will replace this string later. React App You need to enable JavaScript to run this app. {{root}} main code rendered by app.js server, load App.js, generate html code using renderToString, replace part of {{root}} part of import App from'. / src/App';import Koa from 'koa';import React from' react';import Router from 'koa-router';import fs from' fs';import koaStatic from 'koa-static';import path from' path';import {renderToString} from 'react-dom/server' in index.html. / / configuration file const config = {port: 3030}; / / instantiate koaconst app = new Koa () / / static resource app.use (koaStatic (path.join (_ dirname,'.. / build'), {maxage: 365 * 24 * 60 * 1000, index: 'root' / / the configuration here should not be written as' index'', because when accessing localhost:3030, the service cannot load the index.html file by default, and it is easy to fall into a pit. )); / / set routing app.use (new Router () .get ('*', async (ctx, next) = > {ctx.response.type = 'html'; / / specify content type let shtml =''; await new Promise ((resolve, reject) = > {fs.readFile (path.join (_ dirname,'. / build/index.html'), 'utfa8', function (err, data) {if (err) {reject ()) Return console.log (err);} shtml = data; resolve ();});}); / replace the generated HTML ctx.response.body = shtml.replace ('{root}}', renderToString ();}) generated for us by {{root}}) App.listen (config.port, function () {console.log ('server startup, listening port:' + config.port + 'running~');}); config-overrides.js because we are using create-react-app, here we use react-app-rewired to change the configuration of webpack. Because the hash value is automatically added to the resource when performing npm run build, and this hash value is removed during asset-require-hook, which needs to be changed in the configuration, otherwise there will be a problem that the image will not be displayed. This is also a pit, so pay attention to it. Module.exports = {webpack: function (config, env) {/ /... add your webpack config / / console.log (JSON.stringify (config)) / / remove the hash value and solve the asset-require-hook resource problem config.module.rules.forEach (d = > {d.oneOf & & d.oneOf.forEach (e = > {if (e & & e.options & & e.options.name) {e.options.name = e.options.name.replace ('[hash:8].',');}); return config;}}

All right, that's all the code. Isn't that easy? The static resources we read by koa2 are under the build directory. First execute the npm run build packaging project, and then execute node. / server to start the server-side project. Check the HTML code on the http://localhost:3030 page:

There is no {{root}}, the server rendered successfully!

Thank you for reading! This is the end of this article on "sample Analysis of react Server rendering". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report