現在的前端單頁應用,都是通過路由導向到具體的頁面。隨着應用越來越大,頁面也越來越多,首屏加載越來越慢,因為需要下載文件越來越大。這時候就需要通過懶加載分離路由頁面,按需加載。那么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懶加載的一些理解,如有不對,還請各位大佬指點指點。