Skip to content

Latest commit

 

History

History
60 lines (46 loc) · 1.96 KB

File metadata and controls

60 lines (46 loc) · 1.96 KB

代码分割

打包与import

React.lazy

正常的代码是这样引用模块的:
import OtherComponent from './OtherComponent';
之后可以这样引用模块:
const OtherComponent = React.lazy(() => import('./OtherComponent'));

然后应在 React.Suspense 组件中渲染 lazy 组件,如此使得我们可以使用在等待加载 lazy 组件时做优雅降级(如 loading 指示器等)。

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

注意: React.lazy 目前只支持默认导出(default exports)。

举一个使用例子:基于路由的代码分割

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