Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of code segmentation in React

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "what is the method of code segmentation in React", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the method of code segmentation in React".

Preface

In React applications, we usually import a module directly into the page, which results in a large package size. Especially in the case of the introduction of a huge third library, the package volume will be very large. Therefore, we need to pay attention to the code contained in our application to avoid too long loading time due to the large size.

Code segmentation can "lazily load" the content needed by the current user, which can significantly improve the performance of the application. Although it does not reduce the overall code volume of the application, it can avoid loading code that the user will never need, and can reduce the amount of code that needs to be loaded at the initial load.

Import ()

Import () is a method provided by Webpack to split the code. The return result of this method is Promise, and when the file is loaded, you regret the callback of exporting the module to the promise.then method.

For example, there is a math module that exports the add method and the minus method:

Export const add = (a, b) = > {return a + b;} export const minus = (a, b) = > {return a-b;}

A common practice is to introduce modules directly into the page:

Import {add} from'. / math'console.log (add (5,10))

Use import to dynamically import the module:

Import ('. / math') .then ((math) = > {console.log (math.add (5,10))})

Code splitting occurs automatically when Webpack parses to this syntax. If you are using Create React App to create a React application, the import feature is available right out of the box.

Import React, {Component} from 'react';class App extends Component {handleClick = () = > {import ('. / math'). Then ({add}) = > {add (5,10)}) .catch (err = > {/ / Handle failure});}; render () {return (sum of two numbers);}} export default App;React.lazy

The React.lazy method allows us to load components dynamically, helping to reduce the size of the packaged bundle and delay loading components that were not used in the initial rendering.

React.lazy accepts a function that requires a dynamic call to import (). It must return a Promise, which requires a React component of an export default to resolve.

Const AsyncComponent = React.lazy (() = > import ('. / OtherComponent'))

React.lazy returns an asynchronous component that cannot be used alone and needs to be used with React.Suspense. The contents of the fallback in Suspense are displayed when the state of the asynchronous component is pending, and the loaded component is displayed only when resolve. This allows us to gracefully downgrade when using lazy components (such as adding loading effects in fallback, etc.).

Import React, {Suspense} from 'react';const AsyncComponent = React.lazy (() = > import ('. / OtherComponent')); function MyComponent () {return ();} import () + React Loadable

React Loadable is a lightweight code segmentation component, it is a high-level component that allows your application to dynamically load any module before rendering.

Using import () + React Loadable, route segmentation based on react-router version 4.x can be implemented elegantly:

Import Loadable from 'react-loadable';const LoadableBar = Loadable ({loader: () = > import ('. / components/Bar'), loading () {return Loading... ); class MyComponent extends React.Component {render () {return;}}

In actual business development, we usually use some frameworks to develop React applications quickly. In these frameworks, the ability to load on demand is usually provided. Next, let's take a look at demand loading in the UmiJS framework.

UmiJS demand loading

UmiJS is an extensible enterprise front-end application framework, which is based on routing and supports configuration routing and engagement routing. UmiJS encapsulates a dynamic component to implement code segmentation.

Enable demand loading

The demand loading function of UmiJS is turned off by default and needs to be enabled through configuration before use. Add the following configuration to the UmiJS project to enable:

Export default {dynamicImport: {},}

Use demand loading

First encapsulate an asynchronous component:

Import {dynamic} from 'umi';export default dynamic ({loader: async function () {/ / the annotation webpackChunkName here instructs webpack to separate the component HugeA under this name const {default: HugeA} = await import (/ * webpackChunkName: "external_A" * /'. / HugeA'); return HugeA;},})

Then use the encapsulated asynchronous component:

Import React from 'react';import AsyncHugeA from'. / AsyncHugeA';export default () = > {return;} above is the content of this article on "what is the method of code segmentation in React?" I believe you all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report