Home > Web Front-end > JS Tutorial > body text

React server rendering

php中世界最好的语言
Release: 2018-03-23 10:45:54
Original
2053 people have browsed it

This time I will bring you react server rendering. What are the precautions when using react server rendering? The following is a practical case, let’s take a look.

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

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

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

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

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

The entrance of 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

root Create a new .babelrc file in the directory

The content is:

{
 "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 the 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

Is it 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

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

Server.js before modification

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 />)
 ctx.body = str
})
app.listen(3000)
console.log('系统启动,端口:8080')
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 the code of main.js

import React from 'react'
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 components into one Strings of HTML, event binding and other things need to be executed on the browser side
So how do we bind the events?

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

Prepare 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'],
   }
  ]
 }
}
Copy after login

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

那我们就创建一个

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

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

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

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

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

返回出来就好了呗

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

新增一点依赖

cnpm i --save koa-static koa-views ejs
Copy after login
  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 />)
 await ctx.render('index', {
  root: str
 })
})
app.listen(3000)
console.log('系统启动,端口:8080')
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端差别不大

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

推荐阅读:

CSS3实现倾斜和旋转动画效果

not()选择器的使用

box-reflect实现倒影效果

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!