Webpack 在前端開發(fā)中作為模塊打包工具非常受開發(fā)者的青睞,豐富的 loader 使它可以實現(xiàn)各種各樣的功能。本文將通過 webpack 來打包一個 js 文件,看看 webpack 是如何加載各個模塊的。
兩個簡單的源文件
為了方便分析 webpack 加載模塊的原理,我們準(zhǔn)備了兩個文件:
hello.js
const hello = { say: arg => { console.info('hello ' + arg || 'world'); }};export default hello;index.js
import Hello from './hello';Hello.say('man');index.js 作為入口文件,引用了 hello.js 模塊。
Webpack 打包
在命令行執(zhí)行 webpack index.js bundle.js 對入口文件進(jìn)行打包,生成 bundle.js ,大體結(jié)構(gòu)為(為了方便閱讀,我刪除了部分多余的代碼):

可以看到,最終生成的文件以 (function (modules) {})([模塊1, 模塊2]) 的方式啟動,我們定義的模塊被包裝成一個個匿名函數(shù),然后以數(shù)組的形式傳遞個一個匿名函數(shù) function (modules) {},在這個匿名函數(shù)中定義了一個 __webpack_require__() 函數(shù),用來加載模塊,最后,通過 return __webpack_require__(__webpack_require__.s = 0); 來加載第一個模塊 index.js
__webpack_require__() 函數(shù)
該函數(shù)接收一個 moduleId 作為參數(shù),這個參數(shù)就是各個模塊在數(shù)組中的索引,
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; /******/ }其中 installedModules 是用來緩存執(zhí)行過的模塊。通過 modules[moduleId].call() 來執(zhí)行模塊,最后返回模塊的 exports。
模塊接受的參數(shù)
以 hello.js 模塊為例
(function (module, __webpack_exports__, __webpack_require__) { "use strict"; const hello = { say: arg => { console.info('hello ' + arg || 'world'); } }; /* harmony default export */ __webpack_exports__["a"] = (hello); /***/ })webpack 會向模塊傳遞 module, __webpack_exports__, __webpack_require__ 三個參數(shù),前兩個是用來導(dǎo)出模塊內(nèi)的變量,第三個參數(shù)為前面介紹的 __webpack_require__() 的引用,用來導(dǎo)入其它模塊。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答