cutting edge
As our project gets bigger, the size of the code becomes huge, causing our project to load slowly, especially if you include large third-party libraries. You need to pay close attention to includebundle
in order to avoid our project being too large, resulting in long loading time and affecting the user experience. In the React project, we can split the code in the following ways, and we can split the code into small blocks. Make our website faster.
Dynamic loading (import)
es6 provides the import() function, which is executed at runtime, that is, when this sentence is run, the specified module will be loaded.
import() returns a Promise object. In React, we can do this. Through the packaging tool, the packaging process will bePageModuels
Generate separate files, load asynchronously when running
import React, { useState, useEffect } from 'react'; const Index = () => { const [Cmp, setCmp] = useState(null); useEffect(() => { import('./PageModules').then((mod) => setCmp()); }, []); return Cmp ? <Cmp /> : <div>Loading...</div>; };
loadable component
Loadable ComponentsIt is a high-order component that allows you to split the code into smaller blocks and load it on demand. It supports server-side rendering and is simple to use.
import loadable from '@loadable/component' const OtherComponent = loadable(() => import('./OtherComponent')) function MyComponent() { return ( <div> <OtherComponent /> </div> ) }
It and what we'll introduce nextThere are some differences, please refer to/docs/loadab…
React Lazy and React Suspense
React Lazy is an official solution provided by react. It is highly recommended to use this solution for code splitting.In conjunction, this component can specify a loading indicator in case some subcomponents in its component tree do not yet have rendering conditions. How to use it is as follows
// This component is loaded dynamicallyconst OtherComponent = (() => import('./OtherComponent')); function MyComponent() { return ( // Display the <Spinner> component until OtherComponent loads < fallback={<Spinner />}> <div> <OtherComponent /> </div> </> ); }
refer to
- loadable component official website
- React Lazy
Conclusion
If it is a new project and does not require server rendering, it is recommended to use. If server rendering is required, it is recommended to use
loadable component
. Friends can analyze the dependencies of your project, split some modules into independent modules, and reduce the code volume.
The above are detailed explanations of several examples of React code splitting. For more information about React code splitting, please pay attention to my other related articles!