search
HomeWeb Front-endJS TutorialDetailed explanation of the steps to implement react server rendering

This time I will bring you a detailed explanation of the steps to implement react server rendering, and what are the precautions for implementing react server rendering. The following is a practical case, let's take a look.

This article introduces a tutorial on implementing react server rendering from scratch. I hope it can help everyone.

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?

With a realistic and pragmatic attitude, I chose react as the research object (mainly because I wrote too much about vue, 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

To see how it implements server-side rendering, here we go!

Why use server-side rendering

advantage

It’s nothing more than two points

  1. SEO friendly

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

Then the question is what is SEO

In one sentence, most of the websites we build now are SPA websites. All the 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?

Our SEO optimization is also the core described in the following content:

Here are the highlights!

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

Build koa environment

Create a new ssr project and initialize npm

mkdir ssr && cd ssr
npm init

in the project In the following code, we use syntax such as import jsx, which is not supported by the node environment, so babel

needs to be configured. Create new files app.js and index.js in the current project, then

The entrance to babel, the index.js code is as follows

require('babel-core/register')()
require('babel-polyfill')
require('./app')

The entrance to our project, 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")

Create a new .babelrc file in the root directory

The content is:

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

Install the required dependencies

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

Configure startup script

package.json

"scripts": {
 "dev": "nodemon index.js",
}

Here you run npm run dev to open localhost:3000

You will see hello Koa

Is it very simple to start a service?

Install React

cnpm install react react-dom --save

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

Server.js

import Koa from 'koa'
import React from 'react'
import { renderToString } from 'react-dom/server'
import App from './app/main'
const app = new Koa()
// response
app.use(ctx => {
 let str = renderToString(<app></app>)
 ctx.body = str
})
app.listen(3000)
console.log('系统启动,端口:8080')

before modification 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 – actually renders the component into a string

So far, we have not added interactive behaviors such as events to components. Let us try it next

Modify the code of main.js

import React from 'react'
export default class Home extends React.Component {
 render () {
  return <p> window.alert(123)}>hello world</p>
 }
}

Refresh our page again, hey, is it useless?

That's because the backend can only render the component into a string of html, and 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 in the browser

说干就干

配制webpack

在根目录下面新建一个 webpack.config.js

下面是webpack.config.js的内容:

var path = require('path')
var webpack = require('webpack')
module.exports = {
 entry: {
  main: './app/index.js'
 },
 output: {
  filename: '[name].js',
  path: path.join(dirname, 'public'),
  publicPath: '/'
 },
 resolve: {
  extensions: ['.js', '.jsx']
 },
 module: {
  loaders: [
   {test: /\.jsx?$/,
    loaders: ['babel-loader'],
   }
  ]
 }
}

上面的配置将entry设置成了app/index.js文件

那我们就创建一个

下面是app/index.js的代码:

import Demo from './main'
import ReactDOM from 'react-dom'
import React from 'react'
ReactDOM.render(<demo></demo>, document.getElementById('root'))

因为浏览器渲染需要将根组件挂载到某个dom节点上,所以给我们的react代码设置一个入口

这个时候就有一个问题,就是,document对象node环境下并不存在,那怎么解决的呢?

不存在?不存在那我就不用就好了,SSR核心就是让请求的url里面返回具体HTML内容,事件什么的并不care,那么我就把根组件直接renderToString

返回出来就好了呗

下面修改我们的服务代码,让代码支持服务器渲染

新增一点依赖

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

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

  3. ejs:一个模板引擎

修改server.js的代码

import Koa from 'koa'
import React from 'react'
import { renderToString } from 'react-dom/server'
import views from 'koa-views'
import path from 'path'
import Demo from './app/main'
const app = new Koa()
// 将/public文件夹设置为静态路径
app.use(require('koa-static')(dirname + '/public'))
// 将ejs设置为我们的模板引擎
app.use(views(path.resolve(dirname, './views'), { map: { html: 'ejs' } }))
// response
app.use(async ctx => {
 let str = renderToString(<demo></demo>)
 await ctx.render('index', {
  root: str
 })
})
app.listen(3000)
console.log('系统启动,端口:8080')

下面新建我们的渲染模板

新建一个views文件夹

里面新建一个index.html:

nbsp;html>


  <meta>
  <meta>
  <meta>
  <title>Document</title>
  <base>


  <p></p>
  <script></script>

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

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

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

1. 在 package.json里面

新增:

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

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怎么支持呢 => 需要完善的生态

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

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

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

getBoundingClientRect使用方法及兼容性处理

vue的项目结构须知

vue实现购物车的小球抛物线效果详解

The above is the detailed content of Detailed explanation of the steps to implement react server rendering. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use