1.分批打包,按需下载
1.1.bundle:将import的文件merge成一个bundle.
// app.js
import { add } from './math.js';
console.log(add(16, 26)); // 42
// math.js
export function add(a, b) {
return a + b;
}
//Bundle
function add(a, b) {
return a + b;
}
console.log(add(16, 26)); // 42
1.2.code splitting
问题:bundle固然好,但是随着代码的增长,尤其是引入第三方库,bundler会变的越加庞大,为了避免bundler庞大到影响app的加载,需要splitting bundler。
1.2.1 React.lazy()
动态 import 主要用于延迟请求。
webpack 已经支持动态 import,在 create-react-app 和 next.js 中都已经可以使用。
动态 import 主要应用场景是延迟加载方法,对于组件来说,并不是很适用,但是 React.lazy 对于组件的加载则是有比较大的帮助。
//之前
import OtherComponent from './OtherComponent';
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
//之后
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
const OtherComponent = React.lazy(() => import(’./OtherComponent’));会使得在组件渲染的时候,再去加载包含引入路径的组件。
1.2.2. Suspense()
import React, { Component, Suspense } from ‘react’;
要使用 Suspense,需要从react中import。
既然是延迟加载,就会有一个加载过程。
例子:MyComponent包含OtherComponent,当OtherComponent还没有加载完成时,必须使用fallback显示些什么
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
Suspense 使用的时候,fallback 一定是存在且有内容的, 否则会报错。fallback接受任何React元素。可以将Suspense放在任何包含lazy component的地方。甚至可以使用Suspense包裹多个lazy components。
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>
);
}
1.2.3. 基于路由的代码splitting
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
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>
);
React.lazy目前只支持default export.