Simple React SSR

0. Preface

Server-side rendering is not just needed in the project, but sometimes a server-side rendering is also needed. There are many advantages for the project to do server-side rendering

  • The first screen loading is fast, and it has advantages over SPA single page application.
  • SEO optimization is good for crawlers to crawl data.
timg.jpeg

1. introduction

Server side rendering refers to the rendering and generation of the page is completed in the server side, and the rendered page is returned to the client side.

2. installation

When installing, the version is the latest version, and many methods and API s of the new version are deprecated and updated, which makes the final project unable to run. Please refer to the one I uploaded to the good one demo

npm install --save-dev  koa
npm install --save-dev  babel-core
npm install --save-dev  babel-polyfill
npm install --save-dev  babel-preset-latest-node
npm install --save-dev  babel-preset-stage-2
npm install --save-dev  babel-preset-react
# or
yarn add -dev  koa
yarn add -dev  babel-core
yarn add -dev  babel-polyfill
yarn add -dev  babel-preset-latest-node
yarn add -dev  babel-preset-stage-2
yarn add -dev  babel-preset-react

3. configuration

Write a startup file start.js after installation:

// start.js
require('babel-core/register')({
    ignore: [/node_modules/],
    presets: [
        'stage-2',
        'react',
        [
            "latest-node",
            { "target": "current" }
        ]
    ]
});

require('babel-polyfill');
require('./../index');

Write an entry file index.js

// index.js
import Koa from 'koa';
import React from 'react';
import ReactDOMServer from 'react-dom/server';

const { renderToString } = ReactDOMServer;

const app = new Koa();

app.use(ctx => {
    ctx.body = renderToString(
        <div>
            <h1>Hello,World</h1>
        </div>
    );
});

app.listen(3000, () => {
    console.log('server run in 3000');
});

Execute npm start start project

"scripts": {
    "start": "node ./src/start.js"
  },

4. results

Open the browser to view http://localhost:3000/

image.png

5. concluding remarks

A simple React SSR is completed here.

Tags: npm React

Posted on Tue, 03 Dec 2019 20:33:39 -0500 by rachae1