react ssr lazy loading

姚观寿姚观寿
9 min read

English document

An introduction to

Welcome to React-SSR-lazy-Loading documentation!

description:

  1. Cost learning, API is almost the same as REACT API

  2. Pages are loaded on access and loaded on demand, cut from code

  3. Realize the isomorphism of routing, rendering, data and Ajax.

  4. Use webpack-dev-middleware and Webpack-hot-server-middleware to realize hot start compiled memory access

  5. Upgrade of SSR + SPA experience.

  6. Good scalability. React-ssr-lazy-loading is a project constructed by REACT + Webpack. The required plugins and loaders can be matched according to your needs

System requirements

  • Node.js 12.22.0Or higher

  • Supports MacOS, Windows (including WSL), and Linux

    We recommend creating a new application that will set everything up for you automatically. To create a project, run:

git clone https://github.com/qq281113270/react-ssr-lazy-loading.git
cd react-ssr-lazy-loading
npm i
# or
yarn

After the installation is complete ,

Install the required dependencies

npm install

Client Commands

If you don't need SSR rendering, you can choose start:client:dev

Start development commands that do not require SSR server selection

npm  run   start:client:dev

Packaging does not require the SSR server's render online packaging command

npm  run  build:client:prod

SSR server render command

SSR server render development package command : start:ssr:dev

npm  run   start:ssr:dev

SSR server render line pack command build:ssr:prod

npm  run  build:ssr:prod

This command is used to start the SSR server start:server

npm  run  start:server

Project directory Structure:

├── README.md     # documentation
├── bin           # Script execution
│   ├── cmd.js    # Script execution
│   └── index.js
├── client      #  Client Directory react code
│   ├── App      
│   │   ├── App.js
│   │   ├── App.less
│   │   ├── CreateApp.js
│   │   └── index.js
│   ├── assets       # Static resource directory
│   │   ├── css
│   │   ├── img
│   │   └── js
│   ├── component   #  Common Component Directory
│   │   ├── Head
│   │   ├── InitState
│   │   ├── LazyLoadingImg
│   │   ├── Loadable
│   │   ├── Loading
│   │   ├── Nav
│   │   └── Table
│   ├── index.js      # Client entry JS
│   ├── pages        #  Route page Page directory
│   │   ├── Home
│   │   ├── User
│   │   └── marketing
│   ├── public         # Webpack introduces an HTML template directory
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   ├── logo192.png
│   │   └── logo512.png
│   ├── redux        # react-redux directory
│   │   ├── index.js
│   │   ├── initComponentState.js
│   │   └── models
│   ├── router     #  react   directory
│   │   ├── Routers.js
│   │   ├── addRouterApi.js
│   │   ├── history.js
│   │   ├── historyPush.js
│   │   ├── index.js
│   │   ├── react-router-dom
│   │   ├── routePaths.js
│   │   ├── routesComponent.js
│   │   └── routesConfig.js
│   ├── static    # webpack Do not package static resource directories
│   └── utils        # Some tools and methods
│       ├── CheckDataType.js
│       ├── FloatingBall.js
│       ├── SubscribePublished.js
│       ├── createStore.js
│       ├── ergodic.js
│       ├── getBaseInitState.js
│       ├── getCssAttr.js
│       ├── index.js
│       ├── regular.js
│       ├── resolvePath.js
│       ├── setInitData.js
│       ├── stringToObject.js
│       ├── throttlingStabilization.js
│       └── transformRoutePaths.js
├── dist   # Build Code Package directory
│   ├── client  # Client code Build directory
│   └── server  # Server code Build directory
├── node_modules  #node_modules
├── nodemon.json  # nodemon.json   Restarting the Node Configuration
├── package.json    # npm Depend on the package
├── server       # Code directory of the server
│   ├── app.js   #  Server KOA App
│   ├── controller  # The controller
│   ├── index.js   #   Server entry execution file
│   ├── middleware  # Middleware Addition Directory
│   │   ├── clientRouter
│   │   ├── index.js
│   │   └── webpackHot
│   ├── router   # server Routing directory
│   │   ├── api.js  
│   │   └── index.js
│   ├── service    # service directory
│   │   └── user.js
│   └── utils  # Some tool methods on the server side
│       ├── copyFile.js
│       ├── index.js
│       ├── readFile.js
│       └── watchFile.js
├── webpack  # webpack  The configuration directory
│   ├── config
│   │   ├── client # client webpack configuration
│   │   └── server  # server webpack configuration
│   ├── defineLoader # define Loader
│   │   └── MyExampleWebpackLoader.js
│   ├── definePlugin # define Plugin
│   │   ├── HelloWorldCheckerPlugin
│   │   ├── MyExampleWebpackPlugin.js
│   │   ├── react-loadable
│   │   ├── react-loadable-ssr-addon
│   │   ├── webpack-plugin-copy-file
│   │   ├── webpack-plugin-no-require-css
│   │   ├── webpack-plugin-resolve-alias
│   │   └── webpack-plugin-router
│   ├── index.js   # Webpack Export file
│   └── utils  # Webpack tool method
│       ├── alias.js
│       ├── copyFile.js
│       ├── index.js
│       ├── readFile.js
│       ├── readWriteFiles.js
│       ├── stringToObject.js
│       └── watchFile.js

Page configuration and routing

page

├── client      #  Client Directory code
│   ├── pages  
         ├──Home     #   Home page       
         ├── marketing  #  marketing  Directory Secondary Route
                ├── pages
                      ├── DiscountCoupon   # DiscountCoupon page       
                ├── router      
                       ├── routesConfig.js # Configuring Secondary Routes
│   ├── router      # The routing configuration
        ├── routesConfig.js   # Level-1 Route Configuration

If it is to set the level 1 route, then the configuration file is in client --> router --> routesConfig.js

If it's a secondary route then it's in client --> pages --> marketing --> router --> routesConfig.js

routesConfig.js content

import { getHaoKanVideo } from "../assets/js/request/requestApi";
// The routing configuration
export default [
  {
    path: "/",   #  Routing path
    exact: true, # react   Routing parameters exact
    name: "home",  # react routing name
    entry: "/pages/Home/index.js", #   Routing path
    initState: async (parameter = {}) => {  #  Each page initialization data is used for Node background static request data, or the client has just completed the DOM initialization request data
      const { page = 1, size = 10 } = parameter;
      return await getHaoKanVideo({
        page,
        size
      })
        .then((res) => {
          const { result: { list = [], total } = {} } = res;
          return {
            list: list.map((item) => ({
              ...item,
              url: item.userPic
            })),
            total
          };
        })
        .catch(() => {
          // console.log("Error: ", err.message);
        });
    },
    level: 1 #  Routing Level 1 ROUTING, BECAUSE we render the routing points flat, so the level is identified by this number
  },
  {
    path: "/user",
    name: "user",
    entry: "/pages/User/index.js",
    level: 1
  }
];

If we need to add new pages, we can simply add the routesconfig.js parameter to Client Pages after adding the page component.

Webpack automatically generates the RoutesComponent.js file when it is packaged and compiled.

React will fetch the routesComponent.js file. Forming a routing address. Support SSR and pure client development mode.

router

In React Prop, I inject two routing properties. One is pushRoute. One is routePaths routing component address parameter information.

We don't need to use this.props. History.push () in React when routing to a jump

Instead, let's say the name of the home page is home

   { 
    path: "/",   #  路由路径
    exact: true, # react 路由参数exact
    name: "home",  # react 路由 name
    entry: "/pages/Home/index.js", #  路由路径
    }

You can do this using route forwarding

this.pushRoute('home')

If you need to pass parameters get pass parameters

this.pushRoute({
  name:'home',
  query:{
    age:18,
    name:'yao guan shou'
  }
})

Jump for the http://localhost:3002?age=18&name=yaoGuanShou

We can also pass parameters by address

Route Path Configuration

  path: "/:id/:name",
this.pushRoute({
  name:'home',
  params:{
    age:18,
    name:'yao guan shou'
  }
})

Jump for the http://localhost:3002/18/yaoGuanShou

Get Data

Get data and redux

node ssr get per-page data

Data acquisition can be rendered into HTML after Node requests data acquisition and sent directly to the client, where the request can be made.

Configure this if you want to make requests on the Node server. Configured in routesconfig.js

 {
    path: "/",
    exact: true,
    name: "home",
    entry: "/pages/Home/index.js",
    initState: async (parameter = {}) => {  # ajax request
      const { page = 1, size = 10 } = parameter;
      # send ajax request 
      return await getHaoKanVideo({
        page,
        size
      })
        .then((res) => {
          const { result: { list = [], total } = {} } = res;
          return {
            list: list.map((item) => ({
              ...item,
              url: item.userPic
            })),
            total
          };
        })
        .catch(() => {
          // console.log("Error: ", err.message);
        });
    },
    level: 1
  },

Create a new home.js in redux --> models --> home.js to store the Ajax request data.

import { setInitData } from "client/utils";
export default (global) => ({
  state: {
    initState: setInitData(global, "home"),
    count: 0
  },
  reducers: {
    setCount(state, newState) {
      return {
        ...state,
        count: newState
      };
    },

    setInitState(state, newState) {
      return {
        ...state,
        ...newState
      };
    }
  },
  effects: {

  }
});

When the user requests the page, the node server matches the home route, invokes RoutesConfig.js to request initState to send the Ajax request, and stores the data in redux initState.

Read the initState data. Import import {mapRedux} from "client/redux"; The mapRedux decorator, which injects Redux into the component.

import { mapRedux } from "client/redux";

const Index = (props) => {
  let [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const {
    dispatch: { home: { setInitState = () => {} } = {} } = {},
    state: { home: { initState: { list = [] } = {} } = {} } = {}
  } = props;
  console.log("props=======", props);
  return (
    <div className="home"> home </div>
  );
};

Print the props can see props. State. Home. InitState data.

The client updates initState. You have setCount and setInitState at props. Dispatch. home. These are the methods defined in redux --> models --> home.js.

Update initState

 props.dispatch.home.setInitState(newData)

Node SSR Obtains public data

For example, the client header has a data that every page needs, which we can do in the redux -> models -> baseinitstate.js method defined

import { getWeather } from "../../assets/js/request/requestApi";
const setInitData = (global, name) => {
  let initState = {};
  if (global && global.__INITIAL_STATE__ && global.__INITIAL_STATE__[name]) {
    initState = global.__INITIAL_STATE__[name];
  }

  return initState;
};
export default (global) => ({
  state: {
    ...setInitData(global, "baseInitState"),
    menuActive: "/"
  },
  reducers: {
    setInitState(state, newState) {
      return {
        ...state,
        ...newState
      };
    },
    setMenuActive(state, newState) {
      return {
        ...state,
        ...newState
      };
    }
  },
  effects: (dispatch) => ({
    async getWeatherAsync() {
      return await getWeather({
        key: "2d935fc56c5f9ab2ef2165822cedff56",
        city: "440300",
        extensions: "all"
      })
        .then((data) => {
          dispatch.baseInitState.setInitState({
            weather: data.forecasts[0]
          });
          return data;
        })
        .catch((err) => {
          console.log("Error: ", err.message);
        });
    }
  })
});

Effects defines an Ajax request for getWeatherAsync to get the weather data. GetNameAsync must be defined here

It starts with get+name+Async and ends with an Async function because in the framework you're going to match regular functions like this, and then you're going to call that method and send the request, and then you're going to store it in redux.

client get data

To obtain client data, use the useEffect callback just like the React API

function Profile() {
  const [data, setData] = useState(null)
  const [isLoading, setLoading] = useState(false)

  useEffect(() => {
    setLoading(true)
    fetch('/api/profile-data')
      .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [])

  if (isLoading) return <p>Loading...</p>
  if (!data) return <p>No profile data</p>

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.bio}</p>
    </div>
  )
}

The CSS support

This framework has been configured with CSS and LESS. If you need SASS, you can add SASS Loader in the configuration file of Webpack --> config.

The environment variable

.env file public environment variable configuration

.env.development file development environment variable configuration

.env.production file configuration of production environment variables

If you need other environments, you can add the.env.xxxx file and then run the shell script dotenv_config_path=.env.xxxx. Such as:

"cross-env  target='ssr'  npx babel-node  -r  @babel/register    ./dist/server/index.js   -r  dotenv/config  dotenv_config_path=.env.xxxx ",

If you feel good move your finger and click starred for me。 thank you

0
Subscribe to my newsletter

Read articles from 姚观寿 directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

姚观寿
姚观寿