Code Splitting 是什么?
Code-Splitting is a feature supported by bundlers like Webpack and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime
代码拆分可以创建多个 bundle 在运行时加载
Code Splitting 的作用
Code-splitting your app can help you “lazy-load” just the things that are currently needed by the user, which can dramatically improve the performance of your app. While you haven’t reduced the overall amount of code in your app, you’ve avoided loading code that the user may never need, and reduced the amount of code needed during the initial load.
Code Splitting 可以懒加载用户当前需要的代码,因此动态提高了 app 的性能。
使用
import()
最好的使用方式是通过 动态 import()
Before:
import { add } from './math'; console.log(add(16, 26));
After:
import("./math").then(math => { console.log(math.add(16, 26)); });
Note:
The dynamic import() syntax is a ECMAScript >>(JavaScript) proposal not currently part of the language standard. It is expected to be accepted in the near future.
When Webpack comes across this syntax, it automatically starts code-splitting your app. If you’re using Create React App, this is already configured for you and you can start using it immediately. It’s also supported out of the box in Next.js.
当 webpack 遇到这样的语法时,会自动的开始 code-splitting
When using Babel, you’ll need to make sure that Babel can parse the dynamic import syntax but is not transforming it. For that you will need babel-plugin-syntax-dynamic-import.
当使用 Babel 时,需要 babel-plugin-syntax-dynamic-import 插件
Server Rendered Code Splitting 服务器渲染时如何使用 code-splitting
推荐使用 Loadable Components 使用指南
Error Boundaries
如果一个 module 加载失败,会触发一个错误。你可以处理这个错误,并决定如何恢复。一旦你创建了一个 Error Boundaries 你可以在任何一个懒加载组件上使用它
使用示例:
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> );
Route-based Code Splitting 基于路由的 code-splitting
A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.
根据路由使用 code-splitting 是一个好的方式。用户习惯于在页面跳转时花费一定的时间。你可以在这段时间内重新渲染页面,让用户不会在路由跳转的同时和页面互动
这是一个关于如何使用 React Router 和 React.lazy 来实现的例子:
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> );