Home >Web Front-end >JS Tutorial >You are using React lazy imports the wrong way.
This article discusses the optimization strategy of React lazy loading. In a project, the developer initially used the following ways to lazy loading:
<code class="language-javascript">const AnimatedScore = React.lazy(() => import('../components/AnimatedScore')) const FireworksCanvas = React.lazy(() => import('../components/FireworksCanvas')) // ... 其他组件</code>When using NPM Run Build to build a project, it took 3.64 seconds.
In order to optimize the construction speed, the developer uses the
method: map
<code class="language-javascript">const [ AnimatedScore, FireworksCanvas, // ... 其他组件 ] = [ 'AnimatedScore', 'FireworksCanvas', // ... 其他组件名 ].map((component) => React.lazy(() => import(`../components/${component}`)))</code>After modification, the construction time was shortened to 926 milliseconds, which was significantly improved.
The reasons behind:
The use of the method (or
to dynamically generate lazy loading) can allow the packaging tool (such as VITE) to handle all dependencies at one time. Compared with the statement of each component separately, the map
method concentrates all components. This enables the packaging tools to handle these components more effectively and create the required code blocks. reduce
import()
Summary: map
The one -line laziness is loaded to use the method for dynamic introduction, and the main way to optimize the construction process includes:
Reduce the redundant operation during the packaging map
The above is the detailed content of You are using React lazy imports the wrong way.. For more information, please follow other related articles on the PHP Chinese website!