Home >Web Front-end >JS Tutorial >You are using React lazy imports the wrong way.

You are using React lazy imports the wrong way.

DDD
DDDOriginal
2025-01-28 22:38:13411browse

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

Better creation and group code blocks
  • Improve the parallelization efficiency of the creation process of the code block
  • Optimize the reuse of code blocks
  • Do you know the optimization method of this React lazy load? Welcome to share your thoughts in the comments area! ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn