A blog system based on react server-side rendering

Source: Internet
Author: User
Tags node server

System directory and source code to enter

Table of Contents 1. Preparation before development

1.1 Technology Selection
1.2 Overall design
1.3 Building development

2. Technical points

2.1 React
2.2 Redux, React-router
2.3 Server-render

3. Summary Body 1. Preparation 1 before development. 1 Technology Selection

For the personal blog system, the server computing power is often not to be considered, and the I/O operation is more complex, the same as the front-end interaction requirements are also high, so this time mainly around Node系 , the React系 framework for development. For the Internet products after 2016 years, the establishment React of the SPA (single page) and the React-Native construction of similar hybrid native applications, such a development model, will guide the next 3 years of product development.

1.2 Overall design

The diagram depicts a simple, simple, front-end using React + React-router + Redux in flux mode development, the backend uses two Node server to provide React server-side rendering and data supply, here can first look at a server, why to use two, will be mentioned later. If you have the experience of developing a front-end separation project, you can combine the React server-side rendering with the front-end, and we can write Xtpl, Ejs, jade templates to develop smoother.

Because my server is in North China, plus React This series of libraries are very large, even if I will JS, CSS files are packaged into a file, access to the resource load is particularly slow, so the CDN is also essential.

1.3 Building development

After the completion of the design of the project, we need to use the front-end tools to do some beneficial development of the construction, can be broadly divided into the following 3 tasks.

METHOD1:本地服务器的热加载

Development of static component phase in order to improve the development efficiency, reduce the number of small white on the use of F5, we generally use to webpack-dev-server do local services, and the general Webpack configuration file is different from the entry point is entry add something.

entry: {   app: [      ‘webpack-dev-server/client?http://localhost:3000‘,      ‘webpack/hot/only-dev-server‘,      path.resolve(__dirname, ‘../views/index.js‘) ]}

Pass the options in Webpack to the Webpack-dev-server (an express Server) object

new WebpackDevServer(webpack(webpackConfig), {   publicPath: ‘/‘,   hot: true, // 热替换开启 historyApiFallback: true, // 无刷更改url,配合react-router使用 inline: true, // 热替换开启 stats: { colors: true }}).listen(PORT, FUNC);

Then start your server to complete the build.

METHOD2:静态资源分离

The

usually has   at development stage; import./xxx.less   or   require (' xxx.png ')  es5/es6 syntax to introduce static resources, when packaging we need to decouple all static files and our components into a single file, which also requires webpack to complete, and introduce a plug-in named Extract-text-webpack-plugin, using the following

 var extracttextplugin = require (module. export = {module: {loaders: [... //other settings {test: /\.css/, Loader: Extracttextplugin.extract ( "style", [ ' CSS ')}, {test: /\.less/, Loader:ExtractTextPlugin.extract ( ' style ', [ ' CSS ',  ' less ')},]}, plugins: [new Extracttextplugin ( ' [name].css '), ... //Other Settings]}           

METHOD3:服务器端渲染

First of all, it is clear that node stable 4.x version does not support all ES6 syntax, so using ES6 syntax to write node server side, you need to go to ES5 to execute, generally there are two methods. One is babel-node to download to the operating system directly to execute, the second is to use Webpack introduction babel-loader , babel-core packaging (in fact, two methods is a kind of thought). So follow the normal ES6---ES5 build process to package.

module.export = {   node: {      fs: ‘empty‘,      net: ‘empty‘, // 防止打包错乱 __filename: true, __dirname: true }}

If there is a lot of errors in the packaging process about the FS, net module, or after the packaging of the file introduced by the error, add the above webpack option can solve the problem, both of which are in the node-side packaging often occur.

2. Development

Let's take a look at the entire project catalog.

Build: Each of the above building files

Server: Files for server-side rendering

Views: Front-end components and Redux state management file system

2.1 React

For the react syntax is not mentioned here, focus on the organization of the document, so that we develop and daily maintenance. If only for the workload is not large react, the directory is simple, only need to differentiate 展示级组件 (compnent) and 复合型组件 (containers).

---views/

? ---components/each display level component

? ---containers/each composite component

The specific presentation can be seen on GitHub

2.2 Redux, React-router

The beginning of writing react always feel that redux and React-router is a grandstanding, until the data and logic become complex, the background logic is more complex, and the front-end of the react component is like the beginning of the start of the practice, has been doing the top-down data transmission and rendering, Every time we update the data we will request the server, which undoubtedly increased the pressure on the server (for larger applications), and did not play the advantages of react, so-called single-page application is more on paper.

What is the development experience and user experience of combining the three?

Redux

It is Facebook's flux idea of architecture, which is dedicated to the structural problems of software, and provides a very simple and clear idea for react to develop it.

View: View layer (react component)
Action (动作): Messages emitted by the view layer (e.g. MouseClick)
Dispatcher (派发器): Used to receive Actions, execute callback functions
Store (数据层): Used to store the status of the app and, once changed, remind the View to update the page

And Redux provides the action, dispatcher (redux is reducer), the implementation of the store, how to achieve it? Take an example of loading a page of data.

Action.js:loadThisPage is an action creater that can create an object with load_this_page instruction to reducer each time it is called.

  const LOAD_THIS_PAGE = ‘LOAD_THIS_PAGE‘;  const loadThisPage = (pN) => { return { type: LOAD_THIS_PAGE, pN } }

Reducer.js: In reducer, the data in the store is called to change state by judging the command

  const LOAD_THIS_PAGE = ‘LOAD_THIS_PAGE‘;  const articleReducer = (state = {}, action) => {    switch(action.type) {      case LOAD_THIS_PAGE:        return {          allArticles: state.allArticles,          articles: state.allArticles.slice(0, action.pN * 5) }; default: return state; } };

Store.js: Creates a store object that can be passed in to the action by invoking the object's dispatch method.

  import { createStore, applyMiddleware} from ‘redux‘;  const store = createStore(    reducers,    applyMiddleware(thunk) // 若需要redux中间件才添加 );

After the work is done, you also need to associate the store with the component, which means that the component will get the Redux store.

  Import {Provider, connect}From' React-redux ';Connect components and store via connectConst HOMEAPP = connect ((state) = {return {Articles:state.articleReducer.articles,ArticleLen:state.articleReducer.allArticles.length}; }) (Home);Const ROUTES = (<RoutePath="/"Component={Leftarea}><indexroute component={homeapp}/> </Route >); Store is passed through Provider to the React component render (<provider store={store} key=  "index" > <router history={browserhistory} routes={routes}> </Router> </PROVIDER>, document.getElementById (' app ');     

React-router

Compared to redux, react-router understand better, whenever the URL changes, the change is only the components, and not re-refresh the page.

For such a spa, user access only needs to load the data once, then the logic is done by the browser ~ So the interactivity is also a big boost.

2.3 Server Render

Why do I need to implement server render? Which means server-side rendering is better than client rendering?

Server Render vs Client Render

服务器端渲染更利于 SEO ,更容易被爬虫识别

服务器端渲染可以增加访问速度,用户访问时直接推送已经渲染好的 react 页面,不同于客户端渲染的将 react 放入浏览器中渲染。同时减少用户CPU开销,获得更好交互性,解决了首屏加载慢的问题。

分离前后端逻辑,利于开发

How to do react server-side rendering, in fact, Facebook very early to give a solution, and launched the React-dom/server library.

  import { renderToString } from ‘react-dom/server‘;  const html = renderToString(    <Provider store={store}> <RoutingContext {...renderProps} /> </Provider> );

One of the first problems

Why do you use two node servers? Because the information about the database is packaged together and is not secure on the network when Webpack to Node, it is necessary to create another server dedicated to the provision of persistent data services.

3. Summary

This blog post does not have much in-depth exploration of technology, but provides a clearer way to develop ideas, just engaged in development work or small white you may be in the development of a project independently, there are many questions, from building to design, from performance to security are to be considered.

Today's small program is also officially on-line, hurriedly to taste the early adopters ~

Blog system based on react server-side rendering

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.