Build egg react SSR server rendering project from scratch

Time:2020-9-27

Build egg react SSR server rendering project from scratch

1. Initialize the environment

Install node LST (> = 8) environment: https://nodejs.org/zh-cn

2. Initialize the egg project

https://github.com/eggjs/egg-init/blob/master/README.zh-CN.md

npm i egg-init -g egg-init

  • choiceSimple egg app boilerplateProject initializes the egg project
  • newly build${app_root}/app/viewDirectory (egg view specification directory), and add.gitkeepFile to ensure that the empty directory is submitted to the repository by GIT
  • newly build${app_root}/app/view/layout.htmlFile, which is used for client rendering after the server fails to render

<!DOCTYPE html> <html lang=”en”> <head> <title>Egg + React + Webpack</title> <meta name=”keywords”> <meta name=”description”> <meta http-equiv=”content-type” content=”text/html;charset=utf-8″> <meta name=”viewport” content=”initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui”> <link rel=”shortcut icon” href=”/favicon.ico” type=”image/x-icon” /> </head> <body> <div id=”app”></div> </body> </html>

3. Installation dependency

  • Server side rendering dependency

React is not built into egg view react SSR. The project needs to display the installation dependency.

npm i react react-dom axios egg-view-react-ssr egg-scripts –save

  • Build development dependencies

npm i egg-bin cross-env easywebpack-cli easywebpack-react egg-webpack egg-webpack-react –save-dev

  • Install all dependencies

npm install

4. Add configuration

  • add to${app_root}/config/plugin.local.jsto configure

exports.webpack = { enable: true, package: ‘egg-webpack’ }; exports.webpackreact = { enable: true, package: ‘egg-webpack-react’ };

  • add to${app_root}/config/plugin.jsto configure

exports.reactssr = { enable: true, package: ‘egg-view-react-ssr’ };

  • add to${app_root}/config/config.default.jsto configure

‘use strict’; const path = require(‘path’); module.exports = app => { const config = exports = {}; config.keys =’123456′; / / ensure that the static resource files can be accessed config.static = { prefix: ‘/public/’, dir: path.join ( app.baseDir , ‘public’) }; config.reactssr = { layout: path.join ( app.baseDir , ‘app/view/ layout.html ‘) }; return config; }

  • add toeasywebpack-cliconfiguration file${app_root}/webpack.config.js

For entry configuration, please be sure to read this document first: https://www.yuque.com/easy-team/egg-react/config

module.exports = { entry: { ‘home/index’: ‘app/web/page/home/index.jsx’ } };

  • add to${app_root}/.babelrcfile

{ “presets”: [ “react”, [“env”, { “modules”: false }] ], “plugins”: [ “transform-object-assign”, “syntax-dynamic-import”, “transform-object-rest-spread”, [“import”, { “libraryName”: “antd”, “style”: “css” }] ], “env”: { “development”: { “plugins”: [ “react-hot-loader/babel” ] } }, “comments”: false }

Installing Babel related dependencies

npm i babel-core [email protected] –save-dev

npm i babel-preset-env babel-plugin-syntax-dynamic-import babel-plugin-transform-object-assign babel-plugin-transform-object-rest-spread –save-dev

  • add to${app_root}/postcss.config.jsfile(not required)

module.exports = { plugins: [ require(‘autoprefixer’) ] };

Install the autoprefixer dependency

npm i autoprefixer –save-dev

  • add to${app_root}/.gitignoreto configure

.DS_Store .happypack/ node_modules/ npm-debug.log .idea/ dist static public private run *.iml *tmp _site logs .vscode config/manifest.json app/view/* !app/view/layout.html !app/view/.gitkeep package-lock.json

5. Write code

Write the front-end react code

  • newly build${app_root}/app/web/page/home/index.jsxPage file

import React, { Component } from ‘react’; import Layout from ‘component/layout.jsx’; import List from ‘./componets/list’; import ‘./index.css’; export default class HomeIndex extends Component { componentDidMount() { console.log(‘—-componentDidMount—–‘); } render() { return <Layout> <div className=”main”> <div className=”page-container page-component”> <List list={this.props.message}></List> </div> </div> </Layout>; } }

Write node side code

adoptegg-view-react-ssrplug-in unitrenderMethod implementation, see the server-side rendering and front-end rendering mode

  • Create controller file${app_root}/app/controller/home.js

module.exports = app => { return class HomeController extends app.Controller { async server() { const { ctx } = this; // home/ index.js Corresponding to app / Web / page / home/ index.jsx Jsbundle file await after webpack is built ctx.render (‘home/ index.js ‘, { message: ‘egg react server side render’ }); } async client() { const { ctx } = this; //Render client front-end rendering, node layer only does layout.html And resource dependency assembly, rendering to the front-end rendering. You can see the difference between the two by looking at the source code of the running page ctx.renderClient (‘home/ index.js ‘, { message: ‘egg react client render’ }); } }; };

  • Add routing configuration

app.get(‘/’, app.controller.home.server); app.get(‘/client’, app.controller.home.client);

6. Local operation

npm run dev

NPM run dev does three things

  • Start the egg application first
  • Start the webpack (egg webpack) build. The files do not land on the disk, and the built files are all in memory (only start locally, the release mode is to build the files to disk in advance)
  • The build will start two webpack build services at the same time. The client JS builds port 9000 and the server port 9001
  • After the construction, the egg application is officially available, and the browser is opened automatically

7. Release mode

  • ${app_root}/package.jsonAdd command

{ “scripts”: { “dev”: “egg-bin dev”, “start”: “egg-scripts start”, “debug”: “egg-bin debug”, “clean”: “easy clean all”, “build”: “easy build”, }, }

  • The command line runs webpack compilation

NPM run build or easy build prod

  1. Start webpack build, file landing disk
  2. Put the files built by the server intoapp/viewcatalog
  3. The files built by the client are put intopubliccatalog
  4. Generatedmanifest.jsonput toconfigcatalog
  5. The built files are gitignore. Please pay attention to package these files when deploying
  • deploy

Before starting the application, if yes Noegg-scriptsMode start, please setEGG_SERVER_ENVEnvironment variable, local local, test environment settingstest, formal environment settingprod

npm start

8. Projects and plug-ins

  • Egg react webpack boiler framework project based on easywebpack react and egg view react SSR plug-ins
  • Building engineering foundation of easywebpack react webpack react
  • Easy web pack – cli webpack to build engineering scaffold
  • Egg view react SSR plug-in
  • Egg – webpack local open heat update use
  • Egg webpack react native development rendering memory read assist egg webpack react plug-in

9. Suggestions

The above detailed steps just tell you the whole process of egg + react + easywebpack to help clear the process and details. In actual use, it is recommended to use easywebpack cli initialization project or clone egg react webpack boilerplate code to initialize the project.

Recommended Today

Comparison and analysis of Py = > redis and python operation redis syntax

preface R: For redis cli P: Redis for Python get ready pip install redis pool = redis.ConnectionPool(host=’39.107.86.223′, port=6379, db=1) redis = redis.Redis(connection_pool=pool) Redis. All commands I have omitted all the following commands. If there are conflicts with Python built-in functions, I will add redis Global command Dbsize (number of returned keys) R: dbsize P: print(redis.dbsize()) […]