Due to the need for web page SEO, I wanted to transform the previous React project into server-side rendering. After some investigation and research, I consulted a large amount of Internet information. Successfully stepped on the trap. This article mainly introduces to you the detailed server-side rendering transformation of the React project (koa2+webpack3.11). 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.
Selection ideas: To implement server-side rendering, you want to use the latest version of React, and do not make major changes to the existing writing method. If you plan to render on the server-side from the beginning, it is recommended to use the NEXT framework directly. Come and write
Project address: https://github.com/wlx200510/react_koa_ssr
Scaffolding selection: webpack3.11.0 + react Router4 + Redux + koa2 + React16 + Node8.x
Main experience: Become more familiar with React-related knowledge, successfully expand your own technical field, and accumulate server-side technology in actual projects
Notes: Before using the framework, be sure to confirm that the current webpack version is 3.x and Node is 8.x or above. It is best for readers to have used React for more than 3 months and have actual React project experience
Project Directory Introduction
├── assets │ └── index.css //放置一些全局的资源文件 可以是js 图片等 ├── config │ ├── webpack.config.dev.js 开发环境webpack打包设置 │ └── webpack.config.prod.js 生产环境webpack打包设置 ├── package.json ├── README.md ├── server server端渲染文件,如果对不是很了解,建议参考[koa教程](http://wlxadyl.cn/2018/02/11/koa-learn/) │ ├── app.js │ ├── clientRouter.js // 在此文件中包含了把服务端路由匹配到react路由的逻辑 │ ├── ignore.js │ └── index.js └── src ├── app 此文件夹下主要用于放置浏览器和服务端通用逻辑 │ ├── configureStore.js //redux-thunk设置 │ ├── createApp.js //根据渲染环境不同来设置不同的router模式 │ ├── index.js │ └── router │ ├── index.js │ └── routes.js //路由配置文件! 重要 ├── assets │ ├── css 放置一些公共的样式文件 │ │ ├── _base.scss //很多项目都会用到的初始化css │ │ ├── index.scss │ │ └── my.scss │ └── img ├── components 放置一些公共的组件 │ ├── FloatDownloadBtn 公共组件样例写法 │ │ ├── FloatDownloadBtn.js │ │ ├── FloatDownloadBtn.scss │ │ └── index.js │ ├── Loading.js │ └── Model.js 函数式组件的写法 │ ├── favicon.ico ├── index.ejs //渲染的模板 如果项目需要,可以放一些公共文件进去 ├── index.js //包括热更新的逻辑 ├── pages 页面组件文件夹 │ ├── home │ │ ├── components // 用于放置页面组件,主要逻辑 │ │ │ └── homePage.js │ │ ├── containers // 使用connect来封装出高阶组件 注入全局state数据 │ │ │ └── homeContainer.js │ │ ├── index.js // 页面路由配置文件 注意thunk属性 │ │ └── reducer │ │ └── index.js // 页面的reducer 这里暴露出来给store统一处理 注意写法 │ └── user │ ├── components │ │ └── userPage.js │ ├── containers │ │ └── userContainer.js │ └── index.js └── store ├── actions // 各action存放地 │ ├── home.js │ └── thunk.js ├── constants.js // 各action名称汇集处 防止重名 └── reducers └── index.js // 引用各页面的所有reducer 在此处统一combine处理
Project construction ideas
Local development uses webpack-dev-server to achieve hot Update, the basic process is similar to the previous react development, it is still browser-side rendering, so when writing code, you must consider a set of logic and two rendering environments.
After the rendering of the front-end page is completed, its Router jump will not make a request to the server, thereby reducing the pressure on the server. Therefore, there are two ways to enter the page, which must also be considered. The problem of routing isomorphism in two rendering environments.
The production environment needs to use koa as the back-end server to implement on-demand loading, obtain data on the server side, and render the entire HTML, using the latest capabilities of React16 to merge the entire status tree. Implement server-side rendering.
Introduction to local development
The main file involved in checking local development is the index.js file in the src directory to determine the current operating environment. The API of module.hot will only be used in the development environment to implement page rendering update notification when the reducer changes. Pay attention to the hydrate method. This is a new API method specially added for server-side rendering in the v16 version. It Based on the render method, the maximum possible reuse of server-side rendering content is achieved, and the process from static DOM to dynamic NODES is realized. The essence is to replace the process of judging the checksum mark under the v15 version, making the reuse process more efficient and elegant.
const renderApp=()=>{ let application=createApp({store,history}); hydrate(application,document.getElementById('root')); } window.main = () => { Loadable.preloadReady().then(() => { renderApp() }); }; if(process.env.NODE_ENV==='development'){ if(module.hot){ module.hot.accept('./store/reducers/index.js',()=>{ let newReducer=require('./store/reducers/index.js'); store.replaceReducer(newReducer) }) module.hot.accept('./app/index.js',()=>{ let {createApp}=require('./app/index.js'); let newReducer=require('./store/reducers/index.js'); store.replaceReducer(newReducer) let application=createApp({store,history}); hydrate(application,document.getElementById('root')); }) } }
Pay attention to the definition of the window.main function. Combined with index.ejs, you can know that this function is triggered after all scripts are loaded. React-loadable is used in it. The writing method is used for lazy loading of pages. The writing method of packaging pages separately should be explained in conjunction with the routing settings. Here is a general impression. It should be noted that the three methods exposed under the app file are common on the browser side and the server side. The following is mainly about this part of the idea.
Routing processing
Next, look at the following files in the src/app directory. index.js exposes three methods. The three methods involved are in the service It will be used in end-end and browser-end development. This part mainly talks about the code ideas in the router file and the processing of routing by the createApp.js file. This is the key point to achieve mutual communication between the routes at both ends.
routes.js under the router folder is a routing configuration file. It imports the routing configurations under each page and synthesizes a configuration array. You can use this configuration to flexibly control the online and offline pages. The index.js in the same directory is the standard way of writing RouterV4. The routing configuration is passed in by traversing the configuration array. ConnectRouter is a component used to merge Routers. Note that history needs to be passed in as a parameter and needs to be in the createApp.js file. Do separate processing. Let’s take a brief look at several configuration items in the Route component. What’s worth noting is the thunk attribute. This is a key step in achieving rendering after the backend obtains data. It is this attribute that enables components similar to Next to obtain data in advance. Life cycle hooks and other attributes can be found in the relevant React-router documentation and will not be described here.
import routesConfig from './routes'; const Routers=({history})=>( <ConnectedRouter history={history}> <p> { routesConfig.map(route=>( <Route key={route.path} exact={route.exact} path={route.path} component={route.component} thunk={route.thunk} /> )) } </p> </ConnectedRouter> ) export default Routers;
Looking at the code in createApp.js in the app directory, we can find that this framework is processed differently for different working environments. It can only be used in a production environment. The Loadable.Capture method is used to implement lazy loading and dynamically introduce packaged js files corresponding to different pages. At this point, we also need to take a look at how to write the routing configuration file in the component, taking index.js under the home page as an example. Note that /* webpackChunkName: 'Home' */ This string of characters essentially specifies the js file name corresponding to this page after packaging, so for different pages, this comment also needs to be modified to avoid packaging together. The loading configuration item will only take effect in the development environment and will be displayed before the page is loaded. This component can be deleted if it is not needed for actual project development.
import {homeThunk} from '../../store/actions/thunk'; const LoadableHome = Loadable({ loader: () =>import(/* webpackChunkName: 'Home' */'./containers/homeContainer.js'), loading: Loading, }); const HomeRouter = { path: '/', exact: true, component: LoadableHome, thunk: homeThunk // 服务端渲染会开启并执行这个action,用于获取页面渲染所需数据 } export default HomeRouter
这里多说一句,有时我们要改造的项目的页面文件里有从window.location里面获取参数的代码,改造成服务端渲染时要全部去掉,或者是要在render之后的生命周期中使用。并且页面级别组件都已经注入了相关路由信息,可以通过this.props.location来获取URL里面的参数。本项目用的是BrowserRouter,如果用HashRouter则包含参数可能略有不同,根据实际情况取用。
根据React16的服务端渲染的API介绍:
浏览器端使用的注入ConnectedRouter中的history为:import createHistory from 'history/createBrowserHistory'
服务器端使用的history为import createHistory from 'history/createMemoryHistory'
服务端渲染
这里就不会涉及到koa2的一些基础知识,如果对koa2框架不熟悉可以参考我的另外一篇博文。这里是看server文件夹下都是服务端的代码。首先是简洁的app.js用于保证每次连接都返回的是一个新的服务器端实例,这对于单线程的js语言是很关键的思路。需要重点介绍的就是clientRouter.js这个文件,结合/src/app/configureStore.js这个文件共同理解服务端渲染的数据获取流程和React的渲染机制。
/*configureStore.js*/ import {createStore, applyMiddleware,compose} from "redux"; import thunkMiddleware from "redux-thunk"; import createHistory from 'history/createMemoryHistory'; import { routerReducer, routerMiddleware } from 'react-router-redux' import rootReducer from '../store/reducers/index.js'; const routerReducers=routerMiddleware(createHistory());//路由 const composeEnhancers = process.env.NODE_ENV=='development'?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose; const middleware=[thunkMiddleware,routerReducers]; //把路由注入到reducer,可以从reducer中直接获取路由信息 let configureStore=(initialState)=>createStore(rootReducer,initialState,composeEnhancers(applyMiddleware(...middleware))); export default configureStore;
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__这个变量是浏览器里面的Redux的开发者工具,开发React-redux应用时建议安装,否则会有报错提示。这里面大部分都是redux-thunk的示例代码,关于这部分如果看不懂建议看一下redux-thunk的官方文档,这里要注意的是configureStore这个方法要传入的initialState参数,这个渲染的具体思路是:在服务端判断路由的thunk方法,如果存在则需要执行这个获取数据逻辑,这是个阻塞过程,可以当作同步,获取后放到全局State中,在前端输出的HTML中注入window.__INITIAL_STATE__这个全局变量,当html载入完毕后,这个变量赋值已有数据的全局State作为initState提供给react应用,然后浏览器端的js加载完毕后会通过复用页面上已有的dom和初始的initState作为开始,合并到render后的生命周期中,从而在componentDidMount中已经可以从this.props中获取渲染所需数据。
但还要考虑到页面切换也有可能在前端执行跳转,此时作为React的应用不会触发对后端的请求,因此在componentDidMount这个生命周期里并没有获取数据,为了解决这个问题,我建议在这个生命周期中都调用props中传来的action触发函数,但在action内部进行一层逻辑判断,避免重复的请求,实际项目中请求数据往往会有个标识性ID,就可以将这个ID存入store中,然后就可以进行一次对比校验来提前返回,避免重复发送ajax请求,具体可看store/actions/home.js`中的逻辑处理。
import {ADD,GET_HOME_INFO} from '../constants' export const add=(count)=>({type: ADD, count,}) export const getHomeInfo=(sendId=1)=>async(dispatch,getState)=>{ let {name,age,id}=getState().HomeReducer.homeInfo; if (id === sendId) { return //是通过对请求id和已有数据的标识性id进行对比校验,避免重复获取数据。 } console.log('footer'.includes('foo')) await new Promise(resolve=>{ let homeInfo={name:'wd2010',age:'25',id:sendId} console.log('-----------请求getHomeInfo') setTimeout(()=>resolve(homeInfo),1000) }).then(homeInfo=>{ dispatch({type:GET_HOME_INFO,data:{homeInfo}}) }) }
注意这里的async/await写法,这里涉及到服务端koa2使用这个来做数据请求,因此需要统一返回async函数,这块不熟的同学建议看下ES7的知识,主要是async如何配合Promise实现异步流程改造,并且如果涉及koa2的服务端工作,对async函数用的更多,这也是本项目要求Node版本为8.x以上的原因,从8开始就可以直接用这两个关键字。
不过到具体项目中,往往会涉及到一些服务端参数的注入问题,但这块根据不同项目需求差异很大,并且不属于这个React服务端改造的一部分,没法统一分享,如果真是公司项目要用到对这块有需求咨询可以打赏后加我微信讨论。
以Home页面为例的渲染流程
为了方便大家理解,我以一个页面为例整理了一下数据流的整体过程,看一下思路:
服务端接收到请求,通过/home找到对应的路由配置
判断路由存在thunk方法,此时执行store/actions/thunk.js里面的暴露出的函数
异步获取的数据会注入到全局state中,此时的dispatch分发其实并不生效
要输出的HTML代码中会将获取到数据后的全局state放到window.__INITIAL_STATE__这个全局变量中,作为initState
window.__INITIAL_STATE__将在react生命周期起作用前合并入全局state,此时react发现dom已经生成,不会再次触发render,并且数据状态得到同步
服务端直出HTML
The basic process has been introduced. As for the functional writing methods of some Reducers and the positions of actions, they are organized with reference to some analyzes on the Internet. Different people have different opinions. As long as this is in line with your own understanding and helpful for team development Just fine. If you meet the reader background I set at the beginning of the article, I believe that the description in this article is enough for you to illuminate your own server-side rendering technology. It doesn’t matter if you don’t know much about React. You can refer here to supplement some basic knowledge of React.
Related recommendations:
Detailed explanation of React server-side rendering examples
##webpack+react+nodejs server-side rendering_html/css_WEB-ITnose
Vue.js and ASP.NET Core server-side rendering function
The above is the detailed content of Detailed explanation of server-side rendering transformation of React project. For more information, please follow other related articles on the PHP Chinese website!