现在的前端单页应用,都是通过路由导向到具体的页面。随着应用越来越大,页面也越来越多,首屏加载越来越慢,因为需要下载文件越来越大。这时候就需要通过懒加载分离路由页面,按需加载。那么webpack是如果对页面进行懒加载处理的呢?
webpack支持两种动态加载的配置:
1. ECMAScript 的 import() (注意是带()的,带() 表示异步,不带() 表示立即加载)
2. webpack 自带的 require.ensure
下面我们使用import来模拟对文件进行懒加载
// index.js
// 需要安装 @babel/plugin-syntax-dynamic-import 插件
import('./ejs').then(res => {
console.log('ejs: ', res)
})
import('./cjs').then(res => {
console.log('cjs: ', res)
})
// ejs.js
const a = 12
const b = {
a: 1,
b: 2
}
function fn1 (a) {
console.log('fn1 in ejs: ', a)
}
export default fn1
export {
a, b
}
// cjs.js
const a = 1
const b = 2
function fn1 (a) {
console.log('fn1 in cjs: ', a)
}
// module.exports = {
// a, b, fn1
// }
exports.a = a
查看生成的文件,跟不用懒加载一样,是通过一个立即执行函数:
(function(modules) { // webpackBootstrap
// install a JSONP callback for chunk loading
//
function webpackJsonpCallback(data) {
var chunkIds = data[0];
var moreModules = data[1];
// add "moreModules" to the modules object,
// then flag all "chunkIds" as loaded and fire callback
var moduleId, chunkId, i = 0, resolves = [];
for(;i < chunkIds.length; i++) {
chunkId = chunkIds[i];
if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
resolves.push(installedChunks[chunkId][0]);
}
installedChunks[chunkId] = 0;
}
for(moduleId in moreModules) {
if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
modules[moduleId] = moreModules[moduleId];
}
}
if(parentJsonpFunction) parentJsonpFunction(data);
while(resolves.length) {
resolves.shift()();
}
};
// The module cache
var installedModules = {};
// object to store loaded and loading chunks
// undefined = chunk not loaded, null = chunk preloaded/prefetched
// Promise = chunk loading, 0 = chunk loaded
var installedChunks = {
"app": 0
};
// script path function
function jsonpScriptSrc(chunkId) {
return __webpack_require__.p + "js/" + ({}[chunkId]||chunkId) + ".bundle.js"
}
// The require function
function __webpack_require__(moduleId) {
// Check if module is in cache
if(installedModules[moduleId]) {
return installedModules[moduleId].exports;
}
// Create a new module (and put it into the cache)
var module = installedModules[moduleId] = {
i: moduleId,
l: false,
exports: {}
};
// Execute the module function
modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
// Flag the module as loaded
module.l = true;
// Return the exports of the module
return module.exports;
}
// This file contains only the entry chunk.
// The chunk loading function for additional chunks
__webpack_require__.e = function requireEnsure(chunkId) {
var promises = [];
// JSONP chunk loading for javascript
var installedChunkData = installedChunks[chunkId];
if(installedChunkData !== 0) { // 0 means "already installed".
// a Promise means "currently loading".
if(installedChunkData) {
promises.push(installedChunkData[2]);
} else {
// setup Promise in chunk cache
var promise = new Promise(function(resolve, reject) {
installedChunkData = installedChunks[chunkId] = [resolve, reject];
});
promises.push(installedChunkData[2] = promise);
// start chunk loading
var script = document.createElement('script');
var onScriptComplete;
script.charset = 'utf-8';
script.timeout = 120;
if (__webpack_require__.nc) {
script.setAttribute("nonce", __webpack_require__.nc);
}
script.src = jsonpScriptSrc(chunkId);
// create error before stack unwound to get useful stacktrace later
var error = new Error();
onScriptComplete = function (event) {
// avoid mem leaks in IE.
script.onerror = script.onload = null;
clearTimeout(timeout);
var chunk = installedChunks[chunkId];
if(chunk !== 0) {
if(chunk) {
var errorType = event && (event.type === 'load' ? 'missing' : event.type);
var realSrc = event && event.target && event.target.src;
error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
error.name = 'ChunkLoadError';
error.type = errorType;
error.request = realSrc;
chunk[1](error);
}
installedChunks[chunkId] = undefined;
}
};
var timeout = setTimeout(function(){
onScriptComplete({ type: 'timeout', target: script });
}, 120000);
script.onerror = script.onload = onScriptComplete;
document.head.appendChild(script);
}
}
return Promise.all(promises);
};
// expose the modules object (__webpack_modules__)
__webpack_require__.m = modules;
// expose the module cache
__webpack_require__.c = installedModules;
// define getter function for harmony exports
__webpack_require__.d = function(exports, name, getter) {
if(!__webpack_require__.o(exports, name)) {
Object.defineProperty(exports, name, { enumerable: true, get: getter });
}
};
// define __esModule on exports
__webpack_require__.r = function(exports) {
if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
}
Object.defineProperty(exports, '__esModule', { value: true });
};
// create a fake namespace object
// mode & 1: value is a module id, require it
// mode & 2: merge all properties of value into the ns
// mode & 4: return value when already ns object
// mode & 8|1: behave like require
__webpack_require__.t = function(value, mode) {
if(mode & 1) value = __webpack_require__(value);
if(mode & 8) return value;
if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
var ns = Object.create(null);
__webpack_require__.r(ns);
Object.defineProperty(ns, 'default', { enumerable: true, value: value });
if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
return ns;
};
// getDefaultExport function for compatibility with non-harmony modules
__webpack_require__.n = function(module) {
var getter = module && module.__esModule ?
function getDefault() { return module['default']; } :
function getModuleExports() { return module; };
__webpack_require__.d(getter, 'a', getter);
return getter;
};
// Object.prototype.hasOwnProperty.call
__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
// __webpack_public_path__
__webpack_require__.p = "";
// on error function for async loading
__webpack_require__.oe = function(err) { console.error(err); throw err; };
var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
jsonpArray.push = webpackJsonpCallback;
jsonpArray = jsonpArray.slice();
for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
var parentJsonpFunction = oldJsonpFunction;
// Load entry module and return exports
return __webpack_require__(__webpack_require__.s = "./src/js/index.js");
})
/************************************************************************/
({
/***/ "./src/js/index.js":
/*!*************************!*\
!*** ./src/js/index.js ***!
\*************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("// import * as ejs from './ejs'\n// import test from './ejs'\n// import cjs from './cjs'\n// const requireCjs = require('./cjs')\n// const requireEjs = require('./ejs')\n// console.log('cjs: ', cjs)\n// console.log('ejs: ', ejs)\n// console.log('test: ', test)\n// console.log('requireCjs: ', requireCjs)\n// console.log('requireEjs: ', requireEjs)\n// 需要安装 @babel/plugin-syntax-dynamic-import 插件\n__webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./ejs */ \"./src/js/ejs.js\")).then(res => {\n console.log('ejs: ', res);\n});\n__webpack_require__.e(/*! import() */ 0).then(__webpack_require__.t.bind(null, /*! ./cjs */ \"./src/js/cjs.js\", 7)).then(res => {\n console.log('cjs: ', res);\n});\n\n//# sourceURL=webpack:///./src/js/index.js?");
/***/ })
});
先看下立即执行函数传入的参数:
// __webpack_require__.e 这个是什么鬼?其实这个就是实现懒加载的重点,也是跟非懒加载模块的一个区别
__webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./ejs */ "./src/js/ejs.js")).then(res => {
console.log('ejs: ', res);
});
__webpack_require__.e(/*! import() */ 0).then(__webpack_require__.t.bind(null, /*! ./cjs */ "./src/js/cjs.js", 7)).then(res => {
console.log('cjs: ', res);
});
接着看懒加载的函数:
// This file contains only the entry chunk.
// The chunk loading function for additional chunks
__webpack_require__.e = function requireEnsure(chunkId) {
var promises = [];
// JSONP chunk loading for javascript
// 已经加载的chunk数据.如果值为0,表示已经加载过,直接返回Promise.all([]),即直接执行then回调
var installedChunkData = installedChunks[chunkId];
if(installedChunkData !== 0) { // 0 means "already installed".
// a Promise means "currently loading".
// 如果 installedChunkData 不为0 且 有值,说明正在加载中,等待就行
if(installedChunkData) {
promises.push(installedChunkData[2]);
} else {
// setup Promise in chunk cache
// 封装 Promise,因为这里都是基于Promise,所以如果不支持的(说的就是你,IE,需要安装polyfill)
// 将 chunkId 存入 installedChunks 数组,避免重复请求(就是上面if判断)
var promise = new Promise(function(resolve, reject) {
installedChunkData = installedChunks[chunkId] = [resolve, reject];
});
// 将 promise 放入数组,用于后面返回
promises.push(installedChunkData[2] = promise);
// start chunk loading
// 创建 <script> 标签,请求对应的 chunk 文件
var script = document.createElement('script');
var onScriptComplete;
script.charset = 'utf-8';
script.timeout = 120;
if (__webpack_require__.nc) {
script.setAttribute("nonce", __webpack_require__.nc);
}
// 构造 script 路径
script.src = jsonpScriptSrc(chunkId);
// create error before stack unwound to get useful stacktrace later
var error = new Error();
onScriptComplete = function (event) {
// avoid mem leaks in IE.
script.onerror = script.onload = null;
clearTimeout(timeout);
var chunk = installedChunks[chunkId];
if(chunk !== 0) {
if(chunk) {
var errorType = event && (event.type === 'load' ? 'missing' : event.type);
var realSrc = event && event.target && event.target.src;
error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
error.name = 'ChunkLoadError';
error.type = errorType;
error.request = realSrc;
chunk[1](error);
}
installedChunks[chunkId] = undefined;
}
};
// 设置超时,当 chunk 文件下载超时时执行
var timeout = setTimeout(function(){
onScriptComplete({ type: 'timeout', target: script });
}, 120000);
script.onerror = script.onload = onScriptComplete;
// 添加到 head,等待下载完之后执行 chunk 里面的回调就行
document.head.appendChild(script);
}
}
return Promise.all(promises);
};
当chunk文件下载完之后,看下chunk文件:
/*
这个 window.webpackJsonp 是哪来的?干嘛用的呢?
其实这个是在生成的 app.bundle.js 里面定义的,用于下载完 chunk 文件之后的回调:
var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
jsonpArray.push = webpackJsonpCallback;
jsonpArray = jsonpArray.slice();
for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
var parentJsonpFunction = oldJsonpFunction;
注意这里的 webpackJsonp 是一个全局变量,有可能会跟你本身代码或者依赖的模块/库冲突,如果冲突可通过 webpack 配置的 output.jsonpFunction 重新命名
可以看到这个 webpackJsonp 是一个数组,这里重置了它的 push 属性,将其指向 webpackJsonpCallback,用于 模拟 jsonp 回调(jsonp主要是以前用来解决跨域问题的一个方案,具体的可以百度看看)
这里的参数是二维数组,数组的第一个参数是一个数组,表明该文件的chunkId,第二个参数是一个对象,key代表源文件路径,value代表源文件打包之后的内容
*/
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],{
/***/ "./src/js/ejs.js":
/*!***********************!*\
!*** ./src/js/ejs.js ***!
\***********************/
/*! exports provided: default, a, b */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return a; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return b; });\nconst a = 12;\nconst b = {\n a: 1,\n b: 2\n};\n\nfunction fn1(a) {\n console.log('fn1 in ejs: ', a);\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (fn1);\n\n\n//# sourceURL=webpack:///./src/js/ejs.js?");
/***/ })
}]);
接着进来 webpackJsonpCallback 看下这个函数是做什么的:
function webpackJsonpCallback(data) {
// chunkIds 表示需要加载的 chunk 文件对应的id,可能有多个
// moremodules 表示对应的模块,key表示文件路径,value表示模块内容
var chunkIds = data[0];
var moreModules = data[1];
// add "moreModules" to the modules object,
// then flag all "chunkIds" as loaded and fire callback
var moduleId, chunkId, i = 0, resolves = [];
for(;i < chunkIds.length; i++) {
chunkId = chunkIds[i];
// 判断installedChunks里面对应的chunkId是否已经加载过,已经加载过的话,对应的值应该是 installedChunks[chunkId] === 0 即不会跑到if里面
if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
// 如果未加载,在 __webpack_require__.e 函数里面存储的 installedChunks[chunkId] 是一个数组,对应的元素分别是 resolve函数,reject函数,promise对象
// 这里获取对应的 resolve 函数,便于后面resolve掉该promise,触发对应的依赖该模块的then回调
resolves.push(installedChunks[chunkId][0]);
}
// 将 installedChunks[chunkId] 置为0 表示已经加载过,后续依赖该模块的地方直接执行then函数
// 具体实现在 __webpack_require__.e 函数里面
installedChunks[chunkId] = 0;
}
// 遍历 moreModule,并将其加到 modules 里面,便于后面通过 __webpack_require__ 加载该模块
for(moduleId in moreModules) {
if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
modules[moduleId] = moreModules[moduleId];
}
}
// 将该data存入全局的 window["webpackJsonp"] 数组里面
// 这里为啥要存在 window["webpackJsonp"]?是个问题。因为单页面app.bundle.js 就是主入口,也就是只有页面重新加载才会再跑一遍,但是这时候页面重新渲染重新赋值,需要重新构造请求,不存在已加载情况。如果是多页面的话,不会共享同个window。还请高手指点指点
if(parentJsonpFunction) parentJsonpFunction(data);
// resolve Promise 并触发对应的回调,这里对应的就是 app.bundle.js 里面的 __webpack_require__.e(/*! import() */ 1).then(__webpack_require__.bind(null, /*! ./ejs */ "./src/js/ejs.js")) 回调,加载对应的模块
while(resolves.length) {
resolves.shift()();
}
};
接下的逻辑就是正常的执行对应的模块了。
以上就是对于webpack懒加载的一些理解,如有不对,还请各位大佬指点指点。
来源:oschina
链接:https://my.oschina.net/u/4308120/blog/3321037