一文快速弄懂webpack動(dòng)態(tài)import原理
前言
在vue中我們經(jīng)常用到動(dòng)態(tài)導(dǎo)入頁(yè)面組件,那么它是如何實(shí)現(xiàn)的呢,本文將通過(guò)簡(jiǎn)單的案例,快速了解實(shí)現(xiàn)原理
例子
// index.js import('./test').then(fn => { console.log(fn.default()); })
// test.js export default function func() { return 1 }
打包后的代碼包含兩個(gè)文件 bundle.js 和 0.js
點(diǎn)擊展開(kāi)bundle.js
/******/ (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 = { /******/ "main": 0 /******/ }; /******/ /******/ /******/ /******/ // script path function /******/ function jsonpScriptSrc(chunkId) { /******/ return __webpack_require__.p + "" + 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/index.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./src/index.js": /*!**********************!*\ !*** ./src/index.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("__webpack_require__.e(/*! import() */ 0).then(__webpack_require__.bind(null, /*! ./test */ \"./src/test.js\")).then(function (fn) {\n console.log(fn[\"default\"]());\n});\n\n//# sourceURL=webpack:///./src/index.js?"); /***/ }) /******/ });
點(diǎn)擊展開(kāi)0.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ /***/ "./src/test.js": /*!*********************!*\ !*** ./src/test.js ***! \*********************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return func; });\nfunction func() {\n return 1;\n}\n\n//# sourceURL=webpack:///./src/test.js?"); /***/ }) }]);
1. 模塊加載
webpack通過(guò)__webpack_require__加載模塊代碼
// bundle.js function __webpack_require__(moduleId) // 如果模塊已經(jīng)加載,直接返回模塊導(dǎo)出 if(installedModules[moduleId]) { return installedModules[moduleId].exports; } // 模塊導(dǎo)出和模塊信息 var module = installedModules[moduleId] = { i: moduleId, l: false, exports: {} } // 執(zhí)行模塊代碼 modules[moduleId].call(module.exports, module, module.exports, __webpack_require__) module.l = true // 標(biāo)記模塊已經(jīng)加載完成 return module.exports; }
__webpack_require__('index.js')
然后執(zhí)行index.js編譯后的代碼,如下。
Promise.all( [ __webpack_require__.e(0) ] ).then( __webpack_require__.bind(null, "./src/test.js") ).then(function (fn) { console.log(fn.default()); }));
2. jsonp動(dòng)態(tài)加載script
先一步步來(lái),看下__webpack_require__.e這個(gè)方法,它是最先調(diào)用的。
// bundle.js __webpack_require__.e = function requireEnsure(chunkId) { var promises = [] var installedChunkData = installedChunks[chunkId]; // 如果這個(gè)chunk已經(jīng)加載過(guò)了 就不需要加載了 if(installedChunkData !== 0) { // 0 means "already installed" if(installedChunkData) { promises.push(installedChunkData[2]); } else { // 為這個(gè)chunk創(chuàng)建一個(gè)promise var promise = new Promise(function(resolve, reject) { // 記錄這個(gè)chunk對(duì)應(yīng)promise的resolve和reject方法 installedChunkData = installedChunks[chunkId] = [resolve, reject]; }); // promises數(shù)組里添加這個(gè)chunk對(duì)應(yīng)的promise promises.push(installedChunkData[2] = promise) // ============== 動(dòng)態(tài)創(chuàng)建script ================= 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); };
總結(jié)一下,上述代碼做的事情
- 如果chunk沒(méi)有被加載過(guò),會(huì)為這個(gè)chunk創(chuàng)建一個(gè)promise對(duì)象
- 將promise對(duì)象存在promises數(shù)組中
- 將promise的resolve 和 reject存在
installedChunks[chunkId]
中
3. 執(zhí)行異步腳本
經(jīng)過(guò)上面的過(guò)程,會(huì)動(dòng)態(tài)加載0.js的腳本代碼
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ "./src/test.js": (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return func; });\nfunction func() {\n return 1;\n}\n\n//# sourceURL=webpack:///./src/test.js?"); /***/ }) }]);
可以看到window上有一個(gè)webpackJsonp數(shù)組,那么這個(gè)東西是從哪里來(lái)的呢?,我們來(lái)看下面的代碼。
// bundle.js 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;
其實(shí)一開(kāi)始初始化時(shí)已經(jīng)覆蓋實(shí)現(xiàn)了webpackJsonp.push
方法
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ // test.js引入的模塊代碼 }) // 等價(jià)于 webpackJsonpCallback([[0],{ // test.js引入的模塊代碼 })
下面再看看webpackJsonpCallback代碼的實(shí)現(xiàn)
4. webpackJsonpCallback
// bundle.js function webpackJsonpCallback(data) { // chunkid var chunkIds = data[0]; // chunkid對(duì)應(yīng)的模塊 var moreModules = data[1] var moduleId, chunkId, i = 0, resolves = []; for(;i < chunkIds.length; i++) { chunkId = chunkIds[i]; if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { // 收集chunk對(duì)應(yīng)的resolve方法 resolves.push(installedChunks[chunkId][0]); } // 標(biāo)記該chunk已經(jīng)加載 installedChunks[chunkId] = 0; } for(moduleId in moreModules) { if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { // 添加chunk模塊,到全局modules對(duì)象中 modules[moduleId] = moreModules[moduleId]; } } if(parentJsonpFunction) parentJsonpFunction(data) // 依次執(zhí)行chunk對(duì)應(yīng)promise的resolve方法 while(resolves.length) { resolves.shift()(); } };
還是總結(jié)一下上面代碼的過(guò)程
- 收集chunk對(duì)應(yīng)的resolve方法, 前面執(zhí)行__webpack_require__.e時(shí)放在了
installedChunks[chunkId]
里 - 將異步chunk下的所有模塊 添加到 全局modules
- 依次執(zhí)行chunk對(duì)應(yīng)promise的resolve方法
5. 執(zhí)行異步模塊代碼
回到一開(kāi)始index.js的代碼
Promise.all( [ __webpack_require__.e(0) ] ).then( __webpack_require__.bind(null, "./src/test.js") ).then(function (fn) { console.log(fn.default()); }));
經(jīng)過(guò)上面的步驟,此時(shí)promise已經(jīng)resolve了,__webpack_require__.bind(null, "./src/test.js")
會(huì)被執(zhí)行, 此時(shí)異步模塊的代碼已經(jīng)在modules上了,所以可以直接加載。
最后,執(zhí)行fn方法
console.log(fn.default());
流程圖
總結(jié)
webpack動(dòng)態(tài)import的實(shí)現(xiàn)還是比較簡(jiǎn)單的,具體細(xì)節(jié)大家可以自己翻閱下打包后的代碼~
到此這篇關(guān)于webpack動(dòng)態(tài)import原理的文章就介紹到這了,更多相關(guān)webpack動(dòng)態(tài)import原理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端開(kāi)發(fā)必須知道的JS之閉包及應(yīng)用
本文講的是函數(shù)閉包,不涉及對(duì)象閉包(如用with實(shí)現(xiàn))。如果你覺(jué)得我說(shuō)的有偏差,歡迎拍磚,歡迎指教。2010-07-07利用JavaScript做數(shù)獨(dú)的完整實(shí)現(xiàn)過(guò)程
數(shù)獨(dú)游戲是在一個(gè)9*9的方格中進(jìn)行填數(shù)字的游戲,需要滿足的規(guī)則是每行每列和每個(gè)子九宮格都是1~9的不重復(fù)數(shù)字,下面這篇文章主要給大家介紹了關(guān)于如何利用JavaScript做數(shù)獨(dú)的相關(guān)資料,需要的朋友可以參考下2021-09-09OpenLayers3實(shí)現(xiàn)地圖鷹眼以及地圖比例尺的添加
這篇文章主要為大家詳細(xì)介紹了OpenLayers3實(shí)現(xiàn)地圖鷹眼以及地圖比例尺的添加,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09JS/HTML5游戲常用算法之路徑搜索算法 隨機(jī)迷宮算法詳解【普里姆算法】
這篇文章主要介紹了JS/HTML5游戲常用算法之路徑搜索算法 隨機(jī)迷宮算法,結(jié)合實(shí)例形式詳細(xì)分析了針對(duì)迷宮游戲路徑搜索算法的普里姆算法相關(guān)原理、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2018-12-12JavaScript相等運(yùn)算符的九條規(guī)則示例詳解
這篇文章主要給大家介紹了關(guān)于JavaScript相等運(yùn)算符的九條規(guī)則,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用JavaScript具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10JavaScript基于對(duì)象方法實(shí)現(xiàn)數(shù)組去重及排序操作示例
這篇文章主要介紹了JavaScript基于對(duì)象方法實(shí)現(xiàn)數(shù)組去重及排序操作,涉及javascript基于對(duì)象方法的數(shù)組遍歷、比較、去重、排序等相關(guān)操作技巧,需要的朋友可以參考下2018-07-07