webpack代码拆分

2017-10-10  本文已影响0人  Jeremy_zhang

1 前言

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

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

2 什么是代码拆分

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

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

以下会分别讲解

3 分离库代码和业务代码

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

下面分别讲解

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 }
]
上一篇 下一篇

猜你喜欢

热点阅读