一个简单的React server render demo

2018-03-11  本文已影响0人  葶寳寳

1.创建项目react-server-render-demo,然后在根目录下分别创建appsrc文件夹。app文件夹用来存放App组件和入口文件browser.js; src文件夹用来存放server和要渲染的HTML代码。

2.接下来,搭建项目环境,运行一下命令:

npm init -y  //初始化一个package.json文件
npm i webpack -save
npm i webpack-cli -save
npm install react --save-dev
npm install react-dom --save-dev

3.配置webpack

创建webpack.config.js文件内容如下:

module.exports = {
    mode: "development",
    devtool: 'inline-source-map',  //webpack版本更新,要求添加该option,
                           //官网解释:which is good for illustrative purposes
    entry: "./app/browser.js",       //入口文件,就是想要打包的文件入口
    output: {                  //打包后的文件
        path: __dirname,  
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude:/(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};
import React from 'react';
import { hydrate } from 'react-dom';
import App from './App';

hydrate(<App {...window.__APP_INITIAL_STATE__}/>, document.getElementById('root'));
import React, { Component } from 'react';

export default class App extends Component {
  _onModifyUser(){
    alert("hello world");
  }
    render() {
      const { isMobile } = this.props;
  
      return (
        <div>
          <button onClick={this._onModifyUser.bind(this)}>hello world {isMobile ? 'mobile' : 'desktop'}</button>
        </div>
      );
    }
}

4.安装express

npm install express --save

创建 src/server.js 文件内容如下:

import express from 'express';
import React from 'react';
import ReactDOMServer  from 'react-dom/server';

import path from 'path';

import App from '.././app/App';
import template from './template';

const app = new express();

app.use(express.static(path.join(__dirname, '../')));

app.get('/', (req, res) => {
    const isMobile = true;
    const initialState = { isMobile };
    const appString = ReactDOMServer.renderToString(<App {...initialState}/>);
  
    res.send(template({
      body: appString,
      title: 'Hello World from the server',
      initialState: JSON.stringify(initialState)
    }));
  });

app.listen(3000,function(){
    console.log('server is running at 3000');
});

export default app;

5.babel配置

npm install babel-loader --save-dev
npm install babel-core --save-dev  
npm install babel-preset-es2015 --save   
npm install --save-dev babel-preset-react
npm install babel-polyfill --save-dev  
npm install babel-register --save-dev  

创建.babelrc文件内容如下:

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

6.创建src/template.js

export default ({ body, title, initialState }) => {
    return `
      <!DOCTYPE html>
      <html>
        <head>
          <script>window.__APP_INITIAL_STATE__ = ${initialState}</script>
          <title>${title}</title>
        </head>
        
        <body>
          <div id="root">${body}</div>
          <script type="text/javascript" src=".././bundle.js" charset="utf-8"></script>
        </body>
      </html>
    `;
};

7.在根目录下创建index.js:

require('babel-register'); 
require('babel-polyfill');

require('./src/server');

运行

webpack
node index.js

然后访问:http://localhost:3000/

至此该项目已搭建完成

总结

项目中遇到的问题:

改进:

参考文档
Server side rendering with React and Express

上一篇下一篇

猜你喜欢

热点阅读