入门Webpack(六)用一个实例说明代码分割和懒加载

本文旨在用一个简单的实例来说明代码分割和懒加载。

webpack提供了代码分割和懒加载功能,关于这项功能,鄙人认为代码分割是前提,懒加载是结果,只有实现了代码分割,才能懒加载。

那么如何才能实现代码分割呢?需要在一定程度上按照懒加载的需求对原来的代码进行修改。如何修改你需要知道下面的东东。

代码分割可以采用

  • webpack methods : require.ensure || require.include
  • ES2015 loader: System.import 基本废弃变为import || 动态import

require.ensure
官网中所require.ensure()已经被import( )所取代
这个方法接受四个参数

var a = require('normal-dep');

if ( module.hot ) {
  require.ensure(['b'], function(require) {
    var c = require('c');

    // Do something special...
  });
}
  • dependencies: An array of strings declaring all modules required for
    the code in the callback to execute.
  • callback: A function that webpack will execute once the dependencies
    are loaded. An implementation of the require function is sent as a
    parameter to this function. The function body can use this to further
    require() modules it needs for execution.
  • errorCallback: A function that is executed when webpack fails to load
    the dependencies.
  • chunkName: A name given to the chunk created by this particular
    require.ensure(). By passing the same chunkName to various
    require.ensure() calls, we can combine their code into a single
    chunk, resulting in only one bundle that the browser must load.

看完了概念,下面让我们结合就具体的例子来看看代码分割和懒加载。

  1. 新建codeSplit文件夹
  2. npm init初始化
  3. npm install jsonp –save
  4. 新建app.js
  5. 新建webpack.config.json
  6. 当前目录下新建src文件夹
  7. src文件夹下新建dom.js hot.js jsonp.js
  8. 主目录下新建index.html

简要说明:index.html只有一个button按钮,点击会发送ajax请求,请求qq音乐网站热门搜索词条。jsonp.js对第三方库jsonp进行封装,用jsonp是为了实现跨域。点击页面button按钮会发送ajax请求,并将请求到的数据处理后在控制台打印。

  • 代码不分割
//webpack.config.js
var path = require('path')
module.exports = {
    entry: {
        app: './app.js'
    }
    output: {
        path: path.resovle('__dirname', './dist')
        publicPath: './dist/', //这一步不可少,否则代码分割懒加载找不到相应文件
        filename: '[name].bundle.js'
    }
}

代码不分割,打包后会生成app.bundle.js,html中引入该文件。在浏览器中打开会可以看到加载了app.bundle.js,
这里写图片描述
点击button会发送ajax请求,在控制台可以看到信的网络请求和需要打印的信息
这里写图片描述
console.log 的信息
这里写图片描述
上面这个例子是没有进行代码分割和懒加载的。

  • 代码分割

    代码改写分割后,可以看到打包后生成app.bundle.js, dom.js

    这里写图片描述
    可以看到初始页面上加载的app.bundle.js由24.7kb变为6kb,加载时间由8ms变为7ms,复杂的项目中更能体现代码分割和懒加载的优势。
    点击页面button按钮,在控制台的network中可以看到先请求dom.bundle.js,然后发送ajax请求。
    这里写图片描述
    本文用一个简单的实例介绍了代码分割和懒加载,import使用和require.ensure大同小异。我们应该知道的是为什么需要代码分割和懒加载,以及如何实现代码分割和懒加载。

实例源码:https://github.com/TyrionJYQ/Webpack

猜你喜欢

转载自blog.csdn.net/tyrionj/article/details/79280762