When React is packaged with Webpack, a main.js file is generated. As the number of page components increases, main.js becomes larger, slowing down page loading. Using compression-webpack-plugin and Nginx to compress the file, this method works, but when loading the home page, the effect is still not ideal. So, I came up with the idea of splitting main.js into multiple parts. In this way, the js size of the first screen is reduced and the loading speed is accelerated.

No lazy loading

The Index component:

class Index extends React.Component {
   ...
}
export default Index;
Copy the code

Route reference:

import { Route,Switch } from 'react-router-dom'; import indexcomfrom '.. /views/index/index'; class RouterConfig extends React.Component{ render(){ return( <Switch> ... <Route exact path="/" component={ indexcom } /> ... </Switch> ) } } export default RouterConfig;Copy the code

This way of packaging, the code is packaged in main.js.

Use lazy loading

This can be achieved in two ways:

  1. Use Suspense,lazy in React
  2. Use the react – loadable

An error is reported when using route lazy loading to reference CSS with import in components. improt ‘./index.css’ /// main.4d17afb4df2a6b00a18c.js? 4d17afb4df2a6b00a18c:1 Uncaught (in promise) TypeError: Cannot read property ‘call’ of undefined undefined, so the style is referenced in the entry index.js.

The React of Suspense, lazy

  1. Create the main. Js:
 ```
  class Main extends React.Component  {
    
  }
  export const MainCom = Main 
 ```

 
Copy the code
  1. Create maincom. Js
  export { MainCom as default } from "./main";
Copy the code
  1. Routing reference
import { Route,Switch } from 'react-router-dom'; const MainCom = lazy(() => import('.. /views/main/maincom') ); Class RouterConfig extends React.Component{render(){return(<Suspense fallback={<div> >}> <Switch>... <Route exact path="/" component={ MainCom } /> ... </Switch> </Suspense> ) } } export default RouterConfig;Copy the code

react-loadable

  1. The login module:
class Loginextends React.Component {
   ...
}
export default Login;
Copy the code
  1. Routing load
import { Route,Switch } from 'react-router-dom'; import Loadable from 'react-loadable'; const logincom = Loadable({ loader : () => import('.. /views/login/login'), loading() {return <div> loading </div>}, }) class RouterConfig extends React.Component{render(){return(<Suspense fallback={<div> loading </div>}> <Switch>... <Route exact path="/" component={ logincom } /> ... </Switch> </Suspense> ) } } export default RouterConfig;Copy the code