[React SSR 学习笔记 - 01] React SSR 版本的 Hello world

369 阅读1分钟

目的

完成最简单的一个ssr

整体实现思路

  • 写一个简单的hello word 组件
  • 使用 node http 创建一个服务,在响应请求的使用调用react服务端渲染方法 renderToString 方法拿到转换后的 HTML 字符串并返回
  • 使用 babel-cli 模式编译代码
  • node 启动服务

准备工作

安装必要的 react 库和 babel 及插件

使用 babelreact 语法的代码转换成浏览器可识别的代码

npm i react react-dom
npm i @babel/core @babel/cli @babel/preset-react

创建组件

创建一个显示 hello world 的组件

const React = require('react');

//组件
class Index extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h1>hello world !</h1>
  }
}

创建服务

//node http 模块
const http = require('http');

//服务端渲染方法
const { renderToString } = require('react-dom/server');

//创建服务
http.createServer((req, res) => {
        res.writeHead(200, {
            'Content-Type': 'text/html'
        });
        //将组件转换为 html
        const html = renderToString(<Index/>);
        
            res.end(`<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>hello world</title>
        </head>
        <body>
            <div id="root">
               ${html}
            </div>
        </body>
        </html>
`);

    }
).listen(9001);//服务监听9001端口

编译代码

使用 npx 代码可以直接调用模块内的 babel-cli 提供的方法,不用全局安装babel-cli

npx babel index.js -o index-complied.js --presets=@babel/preset-react

输出编译后的代码到 index-complied.js

启动服务

node index-compiled.js

使用浏览器访问,效果如下

image.png