在开发项目中,经常会碰到项目比较大的情况下。项目上线访问时,难免会出现白屏等待时间比较长的情况。那么这个时候就可以考虑使用代码分包了。

原理:import()返回的是一个Promise对象。
作用:减小bundle.js 体积,首屏渲染加快,优化应用的性能;

那么,具体实现代码分包的方式有哪些呢?

(1)采用react自带的lazy懒加载;

import { Suspense, lazy } from 'react'
import { HashRouter, Switch, Route, Redirect } from 'react-router-dom'
import Loading from './loading' //加载中动画组件

const Home = lazy(() => import('./page/home'))
const Detail = lazy(() => import('./page/detail'))
const Cart = lazy(() => import('./page/cart'))

function App() {
  return (
    <div className="App">
      <HashRouter basename='/'>
        <Suspense fallback={<Loading />}>
          <Route path='/Home' component={Home} />
          <Route path='/Detail' component={Detail} />
          <Route path='/Cart' component={Cart} />
          <Redirect to='/Home' />
        </Suspense>
      </HashRouter>
    </div>
  );
}

export default App;

注意:Suspense, lazy是一起出现。

(2)采用三方包react-loadable

import { HashRouter, Switch, Route, Redirect } from 'react-router-dom'
import Loadable from 'react-loadable'
import Loading from './loading' //加载中动画组件

const Home = Loadable({
  loading: () => <Loading />,
  loader: () => import('./page/home')
})
const Detail = Loadable({
  loading: () => <Loading />,
  loader: () => import('./page/detail')
})
const Cart = Loadable({
  loading: () => <Loading />,
  loader: () => import('./page/cart')
})

function App() {
  return (
    <div className="App">
      <HashRouter basename='/'>
          <Route path='/Home' component={Home} />
          <Route path='/Detail' component={Detail} />
          <Route path='/Cart' component={Cart} />
          <Redirect to='/Home' />
      </HashRouter>
    </div>
  );
}

export default App;

(3)自行封装AsyncComponent组件;

import React, { Component, useEffect, useState } from 'react';
import { HashRouter, Switch, Route, Redirect } from 'react-router-dom'
import Loading from './loading'

const AsyncComponent = loadComponent => {
  return class AyncComponent extends Component {
    constructor() {
      super()
      this.state = {
        Com: () => <Loading />,
      }
    }
    componentDidMount() {
      loadComponent().then(res => {
        this.setState({
          Com: res.default
        })
      })
    }
    render() {
      const { Com } = this.state
      return (
        <div>
          <Com />
        </div>
      )
    }
  }
}

const Home = AsyncComponent(() => import('./page/home'))
const Detail = AsyncComponent(() => import('./page/detail'))
const Cart = AsyncComponent(() => import('./page/cart'))

function App() {
  return (
    <div className="App">
      <HashRouter basename='/'>
        <Route path='/Home' component={Home} />
        <Route path='/Detail' component={Detail} />
        <Route path='/Cart' component={Cart} />
        <Redirect to='/Home' />
      </HashRouter>
    </div>
  );
}

export default App;

采用以上任意方法,打包后,代码就会根据路由生成对应的js文件,在我们跳转到相应路由时,异步请求js文件,进行渲染加载。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐