webpack代码拆分

1 前言

这篇文章主要分享使用webpack作为构建工具的SPA项目的代码拆分经验,需要一些基本的webpack知识。

文章内容主要来自于个人开发中的总结以及网上的学习资料,有说的不对或者不准确的地方,欢迎指正。

2 什么是代码拆分

代码拆分是指我们把所有的JS代码拆分为多个JS文件,需要某块代码时再去加载,以加快页面的加载速度.

代码拆分在我看来有三个类型:

  • 库代码和业务代码拆分
  • 不同路由的代码需要拆分
  • 一些特殊操作后才需要显示的内容对应的代码需要拆分

以下会分别讲解

3 分离库代码和业务代码

在开发过程中我们不可避免会使用第三方库,比如JQuery、Vue、React等等,这部分库一般不会发生变化(除非版本升级)。对于这些第三方库的代码,一般有两种处理方式

  • 统一打包到一个chunk中
  • 使用cdn加载

下面分别讲解

3.1 把第三方库打包到统一的chunk

代码如下,以下代码表示把来自node_modules目录的js文件打包到一起,并命名为lib

    new webpack.optimize.CommonsChunkPlugin({
      name: 'lib',
      minChunks: ({ resource }) => (
        resource &&
        resource.indexOf('node_modules') >= 0 &&
        resource.match(/\.js$/)
      )
    }),

3.2 使用cdn加载第三方库

需要使用webpack的externals属性,配置示例如下:

  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'react-router': 'ReactRouter',
    ...
  },

然后在html中需要手动加入script标签来引入,也可以自己写webpack插件来自动生成。我自己写的插件代码如下

function InsertScript(paths) {
  this.paths = paths || []
}

InsertScript.prototype.apply = function (compiler) {
  var paths = this.paths
  compiler.plugin('compilation', function (compilation, options) {
    compilation.plugin('html-webpack-plugin-before-html-processing', function (htmlPluginData, callback) {
      paths.reverse().forEach(function(path) {
        htmlPluginData.assets.js.unshift(path)
      })
      callback(null, htmlPluginData)
    })
  })
}
module.exports = InsertScript

3.3 混合方案

我们引用的第三方库既有react这种稳定的库,也可能引入antd、lodash这种可以按需加载的库。个人觉得对于react这种库适合cdn引入;而antd这种库因为按需加载会造成经常变化,所以适合单独打包。

4 根据路由进行代码拆分(以react为例)

以下是使用对象方式配置react-router的简单例子

import Home from 'path-to-home'
import About form 'path-to-about'

const routes = [
  { path: '/home', component: Home },
  { path: '/about', component: About }
]

4.1 使用require.ensure

针对webpack 1.X版本。进行修改如下

import Home from 'path-to-home'

const About = (location, cb) => {
    require.ensure([], require => {
        cb(null, require('path-to-about').default)
    }, 'about')
}
const routes = [
  { path: '/home', component: Home },
  { path: '/about', getComponent: About }
]

4.2 使用动态import

针对webpack 2.4版本以后,利用import返回的是promise

先编写lazyLoad.js, 如下

// lazyload.js
import React from 'react'

const Loading = () => (
  <div>
   页面加载中....
 </div>
)
const Err = () => (
  <div>
   页面加载失败
 </div>
)
const lazyLoad = (getComponent) => {
  class LazyLoadWrapper extends React.Component {
    state = { Component: undefined }
    componentWillMount () {
      getComponent()
      .then((esModule) => { this.setState({ Component: esModule.default }) })
      .catch(() => { this.setState({ Component: Err }) })
    }
    render () {
      const { Component = Loading } = this.state
      return <Component {...this.props} />
    }
  }
  return LazyLoadWrapper
}
export default lazyLoad

路由配置修改如下

import lazyLoad from 'path-to-lazyload'
import Home from 'path-to-home'

const About = lazyLoad(() => (
  import(/* webpackChunkName: "about" */ 'path-to-about')
))

const routes = [
  { path: '/home', component: Home },
  { path: '/about', component: About }
]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • GitChat技术杂谈 前言 本文较长,为了节省你的阅读时间,在文前列写作思路如下: 什么是 webpack,它要...
    萧玄辞阅读 12,721评论 7 110
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,679评论 25 708
  • 写在开头 先说说为什么要写这篇文章, 最初的原因是组里的小朋友们看了webpack文档后, 表情都是这样的: (摘...
    Lefter阅读 5,330评论 4 31
  • 无意中看到zhangwnag大佬分享的webpack教程感觉受益匪浅,特此分享以备自己日后查看,也希望更多的人看到...
    小小字符阅读 8,243评论 7 35
  • 昨天晚上刷简书,看见同事更的文章,知道她这一天都在家访,一天下来去了将近二十家。原来她以某个学生家为中心点,召集附...
    南国的产物阅读 167评论 0 0