React中的代码分割

代码分割想要解决的问题是:经打包工具📦生成的bundle文件过大,特别是在我们引入第三方库的情况下。

在React中,我们有一下几种解决方案:

1. 动态加载

 1 // math.js
 2 export function add(a, b) {
 3   return a + b
 4 }
 5 
 6 // 未使用动态加载
 7 import { add } from './math.js'
 8 console.log(add(10, 20))
 9 
10 // 使用动态加载
11 import("./math").then(math => {
12   console.log(math.add(5, 16))
13 })

注:如果你使用create-react-app构建程序,则可以直接使用这种语法;如果你使用的是Webpack或者其他打包工具,则需要你按照相应参考文档进行相应配置。使用Babel时,需要babel-plugin-syntax-dynamic-import插件的帮助。

 

2. React.lazy

React.lazy方法可以让我们动态加载组件

1 // 未使用React.lazy
2 import OtherComponent from './OtherComponent'
3 
4 // 使用React.lazy动态引用组件
5 const OtherComponent = React.lazy(() => import('./OtherComponent'))

配合使用Suspense组件(被它包括的组件或元素如果尚未加载,可以先渲染一些加载提示的内容)

 1 const OtherComponent = React.lazy(() => import('./OtherComponent))
 2 
 3 // 使用Suspense
 4 function MyComponent() {
 5   return (
 6     <div>
 7       <Suspense fallback={<div>Loading . . .</div>}>
 8         <OtherComponent />
 9       </Suspense>
10     </div>
11   )
12 }

注:React.lazy和Suspense在SSR中目前还不支持,如果需要在SSR中使用,则需要React Loadable插件的支持。

 

在route过程中使用React.lazy

页面切换和加载通常都需要些时间,所以这里适合使用React.lazy和Suspense的。

 1 import React, { Suspense, lazy } from 'react
 2 import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
 3 
 4 const Home = lazy(() => import('./routes/Home'))
 5 const About = lazy(() => import('./routes/About'))
 6 
 7 const App = () => (
 8   <Router>
 9     <Suspense fallback={<div>Loading . . . </div>}>
10       <Switch>
11         <Route exact path="/" component={Home} />
12         <Route path="/about" component={About} />
13       </Switch>
14     </Suspense>
15   </Router>
16 )

 

详细可参考原文地址:https://reactjs.org/docs/code-splitting.html

posted @ 2018-11-16 11:46  樊顺  阅读(2056)  评论(0编辑  收藏  举报