這篇文章主要介紹了Webpack加載模塊的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
Webpack 在前端開發中作為模塊打包工具非常受開發者的青睞,豐富的 loader 使它可以實現各種各樣的功能。本文將通過 webpack 來打包一個 js 文件,看看 webpack 是如何加載各個模塊的。
兩個簡單的源文件
為了方便分析 webpack 加載模塊的原理,我們準備了兩個文件:
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 打包
在命令行執行 webpack index.js bundle.js 對入口文件進行打包,生成 bundle.js ,大體結構為(為了方便閱讀,我刪除了部分多余的代碼):
可以看到,最終生成的文件以 (function (modules) {})([模塊1, 模塊2]) 的方式啟動,我們定義的模塊被包裝成一個個匿名函數,然后以數組的形式傳遞個一個匿名函數 function (modules) {},在這個匿名函數中定義了一個 __webpack_require__() 函數,用來加載模塊,最后,通過 return __webpack_require__(__webpack_require__.s = 0); 來加載第一個模塊 index.js
__webpack_require__() 函數
該函數接收一個 moduleId 作為參數,這個參數就是各個模塊在數組中的索引,
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 是用來緩存執行過的模塊。通過 modules[moduleId].call() 來執行模塊,最后返回模塊的 exports。
模塊接受的參數
以 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__
三個參數,前兩個是用來導出模塊內的變量,第三個參數為前面介紹的 __webpack_require__()
的引用,用來導入其它模塊。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Webpack加載模塊的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。