On-demand loading of spa based on vue and react

Keywords: React Vue Webpack network

On-demand loading of spa based on vue and react

Since we are planning to use the same login method for all the management systems recently, and then switch the system after login, we don't need every system to re-login once, so the front-end side is thinking about building all the systems with a set of spa applications, but after the integration of each system, the packaged code should be quite large, and a single page needs one-time addition. It seems unrealistic to carry all the resources of the system, so we intend to separate the resources of different systems, and then select the corresponding resources to load the system. I find that this service is similar to the routing of each system, so the configuration of the system is loaded on demand based on vue-router or react-router. So I learned about the application and configuration scheme of on-demand loading.
Based on this business, we have other solutions to welcome exchanges (_O_)

Load on demand

With the development of single-page application, all functions of the whole system are assembled in one page. This page loads all resources at one time. With the continuous expansion of the system, the loaded resources will continue to increase. Although the content of resources will be greatly reduced after compression processing, it can not essentially reduce the increase of the content of resources.
In fact, our module corresponds to different resources, similar to the previous multi-page system, different pages load corresponding resource files, so we can refer to the previous multi-page system approach, in a single-page system according to different modules load their corresponding resource files. That is, what functions the user needs to use at present only loads the code corresponding to this function, that is, so-called on-demand loading.

How to load on demand

In single-page applications, the following principles are generally used for on-demand loading

  • The whole system is divided into a small function, and then divided into several categories according to the degree of function correlation.
  • Merge each class into a Chunk and load the corresponding Chunk on demand
  • For the first screen to see the content directly into the entrance Chunk, in order to reduce the number of web pages first loaded resources
  • Other modules can be loaded on demand.
    The loading of the segmented code requires a certain mechanism to trigger, that is, to load when the user is about to operate to the corresponding function. The load timing of the segmented code needs to be measured and determined by the developer according to the needs of his system.
    Because it takes a certain amount of time to load the segmented code, it can be pre-loaded in advance.
import()

Unlike import(), where import() is different from import xxx from'xxxx', import refers to a function that dynamically loads a module and the parameters passed in are the corresponding modules, but import() returns a Promise object, so it can be processed according to its status after import() is completed.

//eg
import('/component/details').then(mod=>{
    console.log(mod)
},error=>{
    console.log(error)
})
Application of vue on-demand loading

1. Modular Segmentation
According to the situation of the system, the individual divides according to the module of vue-router.

//Partitioning code for roter configuration
import Vue from 'vue'
import Router from 'vue-router'
const listnav=()=> import('@/components/listnav')
const adminav=()=> import('@/components/adminav')
Vue.use(Router)
const router = new Router({
    routes:[{
        path:'/listnav',
        name:'listnav',
        component:listnav
    },
    {
        path:'/adminav',
        name:'adminav',
        component:adminav
    }
    ]
})
export default router

2. Web pack output file configuration

//webpack.base.conf.js
moudle.exports = {
    entry:{
        app:'./src/main.js'
    },
    output:{
        path:"../dist",
        filename:'js/[name].js',
        chunkFilename:'js/[name].js'
    }
}
react on-demand loading application

1. Modular segmentation
The same module can be divided by react-router

//router configuration partitioning code
import React, {PureComponent, Component ,createElement} from 'react';
import {HashRouter as Router, Route,Link,withRouter} from 'react-router-dom';
import Home from "../component/home"
function getAsyncComponent(load) {
  return class AsyncComponent extends PureComponent {
    constructor(props) {
      super(props);
    }
    componentDidMount() {
      // To perform the network loading step only when the higher-order component DidMount
      load().then(({default: component}) => {
      // The code was loaded successfully, the value exported from the code was obtained, and the setState was called to notify the higher-order component to re-render the subcomponent.
        this.setState({
          component,
        })
      });
    }
    render() {
      const {component} = this.state || {};
      // Component is a React.Component type that requires the production of a component instance through React.createElement
      return component ? createElement(component) : null;
    }
  }
}
const Routes = () =>(
    <HashRouter>
        <Route path="/home/:test" exact component={Home}/>
        <Route path='/details/:id' component={getAsyncComponent(
          // Asynchronous loading function, asynchronously loading details components
          () => import('../component/details')
        )}/>
    </HashRouter>
)
export default Routers;

2. Web pack output file configuration

//webpack.base.config.js
module.exports = {
    entry:{
        main: "../src/index.js", //Entry file
    },
    output:{
        path:"../dist",//Export documents
        filename:"js/[name].js",
        chunkFilename:"js/[name].js",
        publicPath: ''
    }
}

3. Pros transfer in on-demand loading components
After load-on-demand partitioning, components loaded on-demand cannot receive props passed in, so parameters brought in by router configuration can not be obtained through this.props.match.params.
The solution uses withRouter in react-router
Configuration processing can be done in components loaded on demand

//component/details.js
import React, { Component } from 'react';
import {withRouter} from 'react-router-dom';
class Details extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        console.log(this.props)
        return (
            <div></div>
        )
    }
}
export default withRouter(Details);
Reference link

vue-router routing lazy loading[ https://router.vuejs.org/zh/guide/advanced/lazy-loading.html]
React loads on demand[ http://webpack.wuhaolin.cn/4%E4%BC%98%E5%8C%96/4-12%E6%8C%89%E9%9C%80%E5%8A%A0%E8%BD%BD.html]
See for more information.

Posted by MDanz on Fri, 10 May 2019 05:18:41 -0700