React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React代码分割

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

作者:码农小菲

虽然一直有做react相关的优化,按需加载、dll 分离、服务端渲染,但是从来没有从路由代码分割这一块入手过,所以下面这篇文章主要给大家介绍了关于React中代码分割的方式,需要的朋友可以参考下

代码分割

React.lazy&Suspense

//使用前:
import OtherComponent from './OtherComponent';
//使用之后:
const OtherComponent = React.lazy(() => import('./OtherComponent'))
   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>
     );
   }

异常捕获边界(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)

// 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"));

到此这篇关于React代码分割的实现方法介绍的文章就介绍到这了,更多相关React代码分割内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文