4.1-大型应用程序的开发
Create by fall on 2021-11-16 Recently revised in 2022-01-01
代码分割
随着应用的增长,代码包也会增长,需要避免因为体积过大导致的加载时间过长。
而一般使用的是 Webpack
,Rollup
进行的打包,这类打包器支持创建多个包,并且在运行时加载。
// 使用之前
import {add} from './math'
console.log(add(66,55))
// 使用之后
import('./math').then(math=>{
console.log(math.add(66,55))
})
Create React App
、Next.js
、Gatsby
支持开箱即用的 Webpack
React.lazy
和 Suspense
技术还不支持服务端渲染
引入代码分割的最佳方式是通过动态 import()
语法
动态引入
使用 React.lazy
导入的内容,需要用 Suspense
进行包裹,如果需要有填充,在 fallback
标签中使用。
imoprt React,{Suspense} from 'react'
const OtherComponent = React.lazy(()=>import('./OtherComponent'))
const MoreComponent = React.lazy(()=>import('./MoreComponent'))
function MyComponent(){
retun(
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent></OtherComponent>
<MoreComponent></MoreComponent>
</Suspense>
</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>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route path="/" component={About}></Route>
</Switch>
</Suspense>
</Router>
)
命名导出
React.lazy
只支持默认导出,如果需要命名导出,需要创建中间模块
// 导出单个组件
export const MyComponent = (<div></div>)
export const MyComponent2 = (<div></div>)
// 作为默认组件导出
export { MyComponent as default} from './ManyComponents.js'
// 导出默认组件
import React,{lazy} from 'react'
参考文章
文章名称 | 地址 |
---|---|
代码分割 | https://react.docschina.org/docs/code-splitting.html |
React快速暴力入门 | https://juejin.cn/post/6960262593265025031#heading-48 |