React代码分割的实现方法介绍

代码分割

  • 打包是个很棒的技术,但随着代码量的增加,容易出现体积过大而导致加载时间过长。为避免这种情况的出现,在前期就思考该问题并对代码包进行分割是个不错的选择。
  • 对应用进行代码分割能够帮助你“懒加载”当前用户所需要的内容,提高应用性能。尽管并没有减少应用整体的代码体积,但可以避免加载用户不需要的代码,并在初始加载的时候减少所需加载的代码量。
  • 简单理解:是性能优化的一种解决方案。比如我们的路由系统中有100个组件,我们在react项目启动时不需要对这100个组件都进行编译,只编译当前URL对应的组件,这就可以用到代码分割的功能;

React.lazy&Suspense

  • 动态引入
//使用前:
import OtherComponent from './OtherComponent';
//使用之后:
const OtherComponent = React.lazy(() => import('./OtherComponent'))
  • 在组件首次渲染时,自动导入包含该组件的包
  • React.lazy 接受一个函数,这个函数需要动态调用import()。它必须返回一个Promist,该Promise 需要resolve 一个default export 的react组件
  • 然后应在 Suspense 组件中渲染 lazy 组件,这样可以在等待加载 lazy 组件时做优雅降级(如 loading 指示器等)
import React, { Suspense } from 'react';
 const OtherComponent = React.lazy(() => import('./OtherComponent'))
 const AnotherComponent = React.lazy(() => import('./AnotherComponent'))
 function MyComponent() {
 return (
 <div>
 <Suspense fallback={<div>Loading...</div>}>
 <section>
 <OtherComponent />
 <AnotherComponent />
 </section>
 </Suspense>
 </div>
 );
 }
  • fallback:接受任何在组件加载过程中你想展示的 React 元素
  • Suspense 组件置于懒加载组件之上的任何位置

异常捕获边界(Error boundaries)

如果模块加载失败(如网络问题),它会触发一个错误。可以通过异常捕获边界(Error boundaries)技术来处理这些情况,以显示良好的用户体验并管理恢复事宜。

import React, { Suspense } from 'react';
import MyErrorBoundary from './MyErrorBoundary';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
const MyComponent = () => (
 <div>
 <MyErrorBoundary>
 <Suspense fallback={<div>Loading...</div>}>
 <section>
 <OtherComponent />
 <AnotherComponent />
 </section>
 </Suspense>
 </MyErrorBoundary>
 </div>
);

基于路由的代码分割

可以选择从路由开始实现代码分割。

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
 <Router>
 <Suspense fallback={<div>Loading...</div>}>
 <Switch>
 <Route exact path="/" component={Home}/>
 <Route path="/about" component={About}/>
 </Switch>
 </Suspense>
 </Router>
);

命名导出(Named Exports)

  • React.lazy 目前只支持默认导出(default exports)
  • 若导出其他模块,可以创建一个中间模块,来重新导出为默认模块
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));
作者:码农小菲原文地址:https://blog.csdn.net/xbczrz/article/details/127925688

%s 个评论

要回复文章请先登录注册