先建立一個最簡單的項目,以後用webpack打包,而後分析打包以後的代碼。javascript
app.js入口文件java
import('./a').then(a=>{ console.log('成功加載a.js文件'); a(); })
a.js 文件webpack
import b from './b.js'; function a() { console.log('this is a.js'); b(); } export default a;
b.js 文件web
function b() { console.log('this is b.js') } export default b;
webpack配置文件(webpack.config.js)json
const path = require('path'); module.exports = { entry: './app.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'main.js', chunkFilename: '[name].bundle.js' } };
打包以後的文件windows
0.bundle.js main.js
main.js的內容promise
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, resolves = [], result; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(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(chunkIds, moreModules, executeModules); /******/ while(resolves.length) { /******/ resolves.shift()(); /******/ } /******/ /******/ }; /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // objects to store loaded and loading chunks /******/ var installedChunks = { /******/ 1: 0 /******/ }; /******/ /******/ // 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 installedChunkData = installedChunks[chunkId]; /******/ if(installedChunkData === 0) { /******/ return new Promise(function(resolve) { resolve(); }); /******/ } /******/ /******/ // a Promise means "currently loading". /******/ if(installedChunkData) { /******/ return installedChunkData[2]; /******/ } /******/ /******/ // setup Promise in chunk cache /******/ var promise = new Promise(function(resolve, reject) { /******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; /******/ }); /******/ installedChunkData[2] = promise; /******/ /******/ // start chunk loading /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ script.timeout = 120000; /******/ /******/ if (__webpack_require__.nc) { /******/ script.setAttribute("nonce", __webpack_require__.nc); /******/ } /******/ script.src = __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".bundle.js"; /******/ var timeout = setTimeout(onScriptComplete, 120000); /******/ script.onerror = script.onload = onScriptComplete; /******/ function onScriptComplete() { /******/ // avoid mem leaks in IE. /******/ script.onerror = script.onload = null; /******/ clearTimeout(timeout); /******/ var chunk = installedChunks[chunkId]; /******/ if(chunk !== 0) { /******/ if(chunk) { /******/ chunk[1](new Error('Loading chunk ' + chunkId + ' failed.')); /******/ } /******/ installedChunks[chunkId] = undefined; /******/ } /******/ }; /******/ head.appendChild(script); /******/ /******/ return promise; /******/ }; /******/ /******/ // 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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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; }; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__.e/* import() */(0).then(__webpack_require__.bind(null, 1)).then(a=>{ console.log('成功加載a.js文件'); a(); }) /***/ }) /******/ ]);
0.bundle.js的內容緩存
webpackJsonp([0],[ /* 0 */, /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__b_js__ = __webpack_require__(2); function a() { console.log('this is a.js'); Object(__WEBPACK_IMPORTED_MODULE_0__b_js__["a" /* default */])(); } /* harmony default export */ __webpack_exports__["default"] = (a); /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function b() { console.log('this is b.js') } /* harmony default export */ __webpack_exports__["a"] = (b); /***/ }) ]);
先來一句歸納的話,webpack模塊化實際上是經過自執行函數啓動,而後經過webpack自定義的exports 和require 來實現的模塊化。對於代碼分割,webpack自定義了一個函數以jsonp的方式加載js文件。下面開始慢慢詳解。服務器
首先咱們先看啓動文件(也就是第一個運行的js文件,這裏是main.js),這個文件會以自執行的方式啓動。我這裏把無關注釋刪除,代碼摺疊以後的截圖。
其實就是一個自執行函數,長這樣的app
(function(modules){})([])
而後咱們看這個自執行函數幹了什麼事情?
此方法是一個回調函數,會用在chunk加載完成以後當即執行這個函數的做用有三個
首先介紹一下變量installedChunks,這個變量記錄了chunk的加載狀況,0表明已經加載 , [resolve,reject]表明着正在加載。因此看下面的for循序,是把chunkIds所有記錄到installedChunks中,並標記爲已經加載
若是executeModule存在,則對其中對應moduleId的模塊進行運行,我這個打包chul出來的文件裏面沒有這塊代碼,估計是由於webpack比較智能。不須要這個功能就把代碼省略了吧。
此函數的做用是根據傳進來的模塊id執行對應模塊的代碼。__webpack_require__上還掛載了其餘一些方法和屬性。
__webpack_require__.e __webpack_require__.m __webpack_require__.c __webpack_require__.d __webpack_require__.n __webpack_require__.o __webpack_require__.p __webpack_require__.oe
上邊這個函數(__webpack_require__)的做用是執行某一模塊,並將其加入到緩存,而後返回模塊的exports
__webpack_require__.e 函數的做用是若是存在代碼分割,那後續的chunk的加載都是使用此函數加載,此函數會建立一個script標籤,並從服務器請求相應的js文件