Home Web Front-end JS Tutorial Explain in detail the issues related to implementing react server rendering

Explain in detail the issues related to implementing react server rendering

Jun 09, 2018 pm 02:14 PM
react

This article mainly introduces the detailed implementation of react server rendering from scratch. Now I will share it with you and give you a reference.

Preface

When I was writing koa recently, I thought, if part of my code provides API and part of the code supports SSR, how should I write it? (If you don’t want to split it into two services)
And I have also used some server-side rendering in the projects I wrote 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 truth-seeking and pragmatic attitude, I chose react as the research object (mainly because Vue has been written a bit 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

Let’s see how it implements server-side rendering, here we go!

Why use server-side rendering

Advantages

It’s nothing more than two points

  1. SEO Friendly

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

Then the question is what is SEO

One sentence introduction is that 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, they find that they are all 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 for mounting.

Build the koa environment

New An ssr project, and initialize npm

1

2

mkdir ssr && cd ssr

npm init

Copy after login

In the following code, we use import jsx and other syntaxes, which are not supported by the node environment, so we need to configure babel

Create a new one in the current project Files app.js and index.js, and then

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

1

2

3

4

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

 

require('babel-polyfill')

require('./app')

Copy after login

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

1

2

3

4

5

6

7

8

9

10

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

root Create a new .babelrc file in the directory

The content is:

1

2

3

{

 "presets": ["react", "env"]

}

Copy after login

Install the dependencies required above

1

2

npm install babel-core babel-polyfill babel-preset-env babel-preset-react nodemon --save-dev

npm i koa --save

Copy after login

Configure the startup script

package.json

1

2

3

"scripts": {

 "dev": "nodemon index.js",

}

Copy after login

Here you run npm run dev and open localhost:3000

You will see hello Koa

Is it very simple to start a service

Install React

1

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

1

2

3

4

5

6

7

import React from 'react'

 

export default class Home extends React.Component {

 render () {

  return <p>hello world</p>

 }

}

Copy after login

Server.js before modification

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

Open chrome developer The tool checks 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

1

2

3

4

5

6

7

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 render the component into a string of html. Event binding and other things need to be executed 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 the content of webpack.config.js:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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:

1

2

3

4

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 needs to mount the root component to a certain dom node, we set an entrance for our react code

There is a problem at this time, that is, the document object node environment is not If it doesn't exist, 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 or anything like that, so I just return the root component directly to renderToString

.

Let’s modify our service code to support server rendering

Add some dependencies

1

cnpm i --save koa-static koa-views ejs

Copy after login
  1. koa-static: In the middle of processing static files File

  2. koa-views: middleware for configuring templates

  3. ejs: a template engine

Modify the code of server.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

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

Create our rendering template below

Create a views folder

Create a new index.html in it:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<!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

You can put some variables in this html, such as this <%- root %>, which is where the renderToString result will be placed later.

/main.js is the code built by react

Let’s test our code directly

1. In package.json

新增:

1

2

3

4

"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端差别不大

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在vue中如何实现页面跳转后返回原页面初始位置

使用vue-router如何设置每个页面的title方法

如何解决Vue.js显示数据的时,页面闪现

The above is the detailed content of Explain in detail the issues related to implementing 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 build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to build real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

See all articles