Home Web Front-end JS Tutorial Implement basic methods of react server rendering

Implement basic methods of react server rendering

Jan 31, 2018 am 10:23 AM
react Base server

This article mainly introduces you to the detailed implementation of react server rendering from scratch. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Preface

When I was writing koa recently, I thought, if part of my code provides API and part of the code supports SSR, then how should I write it? Woolen cloth? (If you don’t want to split it into two services)
And I have also used some server-side rendering in the projects I have written recently, such as nuxt, and I have also worked on next projects. It is true that the development experience is very friendly, but friendly is still friendly. , how is it implemented specifically? Have you ever considered it?

Based on a pragmatic attitude, I chose react as the research object (mainly because Vue has been written too much, which is disgusting). Then I will simply write a react server-side rendering demo at the minimum cost.

Technology stack used

react 16 + webpack3 + koa2

Look at how it implements server-side rendering Yes, here we go!

Why use server-side rendering

Advantages

It’s nothing more than two points

  1. SEO friendly

  2. Speed ​​up first screen rendering and reduce white screen time

Then the question arises What is SEO

In one sentence, most of the websites we make now are SPA websites. All pages and data come from ajax. When the search engine spider comes to collect the web pages, , found completely empty? So do you think the weight and effect of your website's inclusion are good or bad?

The core of our SEO optimization is also described in the following content:

The following is the key point!

Let the server return the HTML with content to us. If the event occurs, the browser will render it again to mount it

Build the koa environment

Create a new ssr project and initialize npm in the project


mkdir ssr && cd ssr
npm init
Copy after login

In the following code we use syntax such as import jsx, which is not supported by the node environment. So you need to configure babel

Create new files app.js and index.js in the current project, and then

babel’s entrance, the index.js code is as follows


require('babel-core/register')()

require('babel-polyfill')
require('./app')
Copy after login

The entrance to our project, the app.js code is as follows


import Koa from 'koa'
const app = new Koa()

// response
app.use((ctx) => {
 ctx.body = 'Hello Koa'
})

app.listen(3000)
console.log("系统启动,端口:3000")
Copy after login

Create a new .babelrc file in the root directory

Content Yes:


{
 "presets": ["react", "env"]
}
Copy after login

Install the dependencies required above


npm install babel-core babel-polyfill babel-preset-env babel-preset-react nodemon --save-dev
npm i koa --save
Copy after login

Configure startup script

package .json


"scripts": {
 "dev": "nodemon index.js",
}
Copy after login

Here you run npm run dev and open localhost:3000

You will see hello Koa

Yes It is not very simple to start a service

Install React


##

cnpm install react react-dom --save
Copy after login

Create a new app folder in the root directory , and create a new main.js in the folder

The main.js code is as follows


import React from 'react'

export default class Home extends React.Component {
 render () {
  return <p>hello world</p>
 }
}
Copy after login

Before modifying server.js


import Koa from &#39;koa&#39;
import React from &#39;react&#39;
import { renderToString } from &#39;react-dom/server&#39;
import App from &#39;./app/main&#39;

const app = new Koa()

// response
app.use(ctx => {
 let str = renderToString(<App />)

 ctx.body = str
})

app.listen(3000)

console.log(&#39;系统启动,端口:8080&#39;)
Copy after login

At this time, npm run dev


You will see hello world appear on the screen

Then open the chrome developer tools to view our Request:

Our simplest react component becomes str and passed in

Here we use a method:


renderToString - In fact, it is to render the component into a string

So far, we have not added events and other interactive behaviors to the component. Let us try it next

Modify main. js code


import React from &#39;react&#39;

export default class Home extends React.Component {
 render () {
  return <p onClick={() => window.alert(123)}>hello world</p>
 }
}
Copy after login

Refresh our page again, hey, is it useless?

That’s because the backend can only talk about components Rendering into a string of html, event binding and other things need to be performed on the browser side

So how do we bind the event?

Then you will definitely guess that since the server renders a string of html, the way to mount the event is to re-render it once in the browser

Just do it Do

Configure webpack

Create a new webpack.config.js under the root directory


The following is webpack.config. js content:


var path = require(&#39;path&#39;)
var webpack = require(&#39;webpack&#39;)

module.exports = {
 entry: {
  main: &#39;./app/index.js&#39;
 },
 output: {
  filename: &#39;[name].js&#39;,
  path: path.join(__dirname, &#39;public&#39;),
  publicPath: &#39;/&#39;
 },
 resolve: {
  extensions: [&#39;.js&#39;, &#39;.jsx&#39;]
 },
 module: {
  loaders: [
   {test: /\.jsx?$/,
    loaders: [&#39;babel-loader&#39;],
   }
  ]
 }
}
Copy after login

The above configuration sets the entry to the app/index.js file

Then we will create one

The following is the code of app/index.js:


import Demo from &#39;./main&#39;
import ReactDOM from &#39;react-dom&#39;
import React from &#39;react&#39;
ReactDOM.render(<Demo />, document.getElementById(&#39;root&#39;))
Copy after login

Because browser rendering requires mounting the root component to a dom node, the react code given to us Setting up an entrance

There is a problem at this time, that is, the document object does not exist in the node environment, so how to solve it?

does not exist? If it doesn’t exist, then I don’t need it. The core of SSR is to return specific HTML content in the requested URL. I don’t care about events, so I just return the root component directly to renderToString


. Okay

Let’s modify our service code so that the code supports server rendering

Add some dependencies


cnpm i --save koa-static koa-views ejs
Copy after login
  1. koa-static: 处理静态文件的中间件

  2. koa-views: 配置模板的中间件

  3. ejs:一个模板引擎

修改server.js的代码


import Koa from &#39;koa&#39;
import React from &#39;react&#39;
import { renderToString } from &#39;react-dom/server&#39;
import views from &#39;koa-views&#39;
import path from &#39;path&#39;

import Demo from &#39;./app/main&#39;
const app = new Koa()
// 将/public文件夹设置为静态路径
app.use(require(&#39;koa-static&#39;)(__dirname + &#39;/public&#39;))
// 将ejs设置为我们的模板引擎
app.use(views(path.resolve(__dirname, &#39;./views&#39;), { map: { html: &#39;ejs&#39; } }))

// response
app.use(async ctx => {
 let str = renderToString(<Demo />)
 await ctx.render(&#39;index&#39;, {
  root: str
 })
})

app.listen(3000)

console.log(&#39;系统启动,端口:8080&#39;)
Copy after login

下面新建我们的渲染模板

新建一个views文件夹

里面新建一个index.html:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <base href="/client" rel="external nofollow" >
</head>
<body>
  <p id="root"><%- root %></p>
  <script src="/main.js"></script>
</body>
</html>
Copy after login

这个 html 里面可以放一些变量,比如这个<%- root %>,就是等下要放renderToString结果的地方

/main.js则是react构建出来的代码

下面直接来测试一下我们的代码

1. 在 package.json里面

新增:


 "scripts": {
  "dev": "nodemon index.js",
  "build": "webpack"
 },
Copy after login

2. 运行 npm run build, 构建出我们的react代码

3. npm run dev

点击一下代码,是不是会 alert(123)

 tada 撒花,恭喜你,一个最简单服务器渲染就已经完成

到这里核心的思想就都已经讲完了,总结来说就下面三点:

  1. 起一个node服务

  2. 把react 根组件 renderToString渲染成字符串一起返回前端

  3. 前端再重新render一次

原理就是这么简单

但是具体开发的时候还会有各种各样的需求,比如:

  1. 不可能我每次改完代码都重新构建看效果吧 => 需要 实时构建

  2. create-react-app 都是热更新,你还要刷新是不是太蠢了 => 需要支持热更新

  3. 其他一些配套的周边,如: react-router, redux 或者mobx怎么支持呢 => 需要完善的生态

.etc

这些问题都是用完 官方脚手架之后就回不去了的,所以更多的配置可以参考下面的repo(是一个工具链完善的最小实现),欢迎提PR

GitHub - ws456999/koa-react-ssr-starter: to understand && to explain how react ssr works

目前你可以在里面找到 react + react-router + mobx + postcss + 热更新的配置,除了react-router的配置有些差别,其他都跟client端差别不大

相关推荐:

react后端渲染模板引擎noox发布使用方法

React前后端同构防止重复渲染

浏览器渲染性能优化

The above is the detailed content of Implement basic methods of react server rendering. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure Dnsmasq as a DHCP relay server How to configure Dnsmasq as a DHCP relay server Mar 21, 2024 am 08:50 AM

The role of a DHCP relay is to forward received DHCP packets to another DHCP server on the network, even if the two servers are on different subnets. By using a DHCP relay, you can deploy a centralized DHCP server in the network center and use it to dynamically assign IP addresses to all network subnets/VLANs. Dnsmasq is a commonly used DNS and DHCP protocol server that can be configured as a DHCP relay server to help manage dynamic host configurations in the network. In this article, we will show you how to configure dnsmasq as a DHCP relay server. Content Topics: Network Topology Configuring Static IP Addresses on a DHCP Relay D on a Centralized DHCP Server

Best Practice Guide for Building IP Proxy Servers with PHP Best Practice Guide for Building IP Proxy Servers with PHP Mar 11, 2024 am 08:36 AM

In network data transmission, IP proxy servers play an important role, helping users hide their real IP addresses, protect privacy, and improve access speeds. In this article, we will introduce the best practice guide on how to build an IP proxy server with PHP and provide specific code examples. What is an IP proxy server? An IP proxy server is an intermediate server located between the user and the target server. It acts as a transfer station between the user and the target server, forwarding the user's requests and responses. By using an IP proxy server

What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline What should I do if I can't enter the game when the epic server is offline? Solution to why Epic cannot enter the game offline Mar 13, 2024 pm 04:40 PM

What should I do if I can’t enter the game when the epic server is offline? This problem must have been encountered by many friends. When this prompt appears, the genuine game cannot be started. This problem is usually caused by interference from the network and security software. So how should it be solved? The editor of this issue will explain I would like to share the solution with you, I hope today’s software tutorial can help you solve the problem. What to do if the epic server cannot enter the game when it is offline: 1. It may be interfered by security software. Close the game platform and security software and then restart. 2. The second is that the network fluctuates too much. Try restarting the router to see if it works. If the conditions are OK, you can try to use the 5g mobile network to operate. 3. Then there may be more

PHP, Vue and React: How to choose the most suitable front-end framework? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

How to install PHP FFmpeg extension on server? How to install PHP FFmpeg extension on server? Mar 28, 2024 pm 02:39 PM

How to install PHPFFmpeg extension on server? Installing the PHPFFmpeg extension on the server can help us process audio and video files in PHP projects and implement functions such as encoding, decoding, editing, and processing of audio and video files. This article will introduce how to install the PHPFFmpeg extension on the server, as well as specific code examples. First, we need to ensure that PHP and FFmpeg are installed on the server. If FFmpeg is not installed, you can follow the steps below to install FFmpe

Detailed explanation of the advantages and utility of Golang server Detailed explanation of the advantages and utility of Golang server Mar 20, 2024 pm 01:51 PM

Golang is an open source programming language developed by Google. It is efficient, fast and powerful and is widely used in cloud computing, network programming, big data processing and other fields. As a strongly typed, static language, Golang has many advantages when building server-side applications. This article will analyze the advantages and utility of Golang server in detail, and illustrate its power through specific code examples. 1. The high-performance Golang compiler can compile the code into local code

Equipped with AMD EPYC 4004 series processors, ASUS launches a variety of server and workstation products Equipped with AMD EPYC 4004 series processors, ASUS launches a variety of server and workstation products Jul 23, 2024 pm 09:34 PM

According to news from this website on July 23, ASUS has launched a variety of server and workstation-level products powered by AMD EPYC 4004 series processors. Note from this site: AMD launched the AM5 platform and Zen4 architecture EPYC 4004 series processors in May, offering up to 16-core 3DV-Cache specifications. ASUSProER100AB6 server ASUSProER100AB6 is a 1U rack server product equipped with EPYC Xiaolong 4004 series processor, suitable for the needs of IDC and small and medium-sized enterprises. ASUSExpertCenterProET500AB6 workstation ASUSExpertCenterProET500AB6 is a

See all articles