笔记记录

杂记

create-react-app项目打包优化

介绍

本文中针对使用create-react-app创建的项目进行项目打包优化,有关Vue项目中的打包优化可以参考Vue-Cli3+eleUI项目打包优化。

路由懒加载

默认情况下,当下项目根路径下执行npm run build时,create-react-app内部使用webpack将src/路径下的所有代码打包成一个JS文件和一个CSS文件。
当项目代码量过多时,这样就不合适了。
试想,当用户访问登录页面时,浏览器加载的JS文件还包含其他页面的代码,这会延长网页的加载时间,给用户带来不好的体验。
理想情况下,当用户访问一个页面时,该页面应该只加载自己使用到的代码,所以我们需要代码分片,将JS代码分片打包到多个文件中,然后在访问页面时按需加载。
如何实现呢?
新建一个专门用来懒加载导入的文件

// asyncComponent.js
import React, { Component } from 'react'

export default function asyncComponent (importComponent) {
  class AsyncComponent extends Component {
    state = {
      component: null // 动态加载的组件
    }
    componentDidMount () {
      importComponent().then(mod => {
        this.setState({
          component: mod.default ? mod.default : mod
        })
      })
    }
    render () {
      // 渲染动态加载的组件
      const C = this.state.component
      return C ? <C {...this.props} /> : null
    }
  }
  return AsyncComponent
}

路由文件中使用

// router/index.js
import asyncComponent from './asyncComponent'
const Login =  asyncComponent(() => import('../views/login'))

const appRoutes = [
  {
    path: '/login',
    component: Login
  }
]

export { appRoutes }

会看到打包后的js文件的chunk会被分成好多个代码分片。

在这里插入图片描述

给chunk命名

我们看webpack中对打包的chunkName的配置

在这里插入图片描述

对,name没有生效,自动生成的都是数字。
所以,这里又用到了Magic Comments魔术注释法

// router/index.js
import asyncComponent from './asyncComponent'

const Login =  asyncComponent(() => import(/* webpackChunkName: 'login' */ '../views/login'))

这样[name]就被我们自定义啦!

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.5.2 Zero

Copyright Your WebSite.Some Rights Reserved.