国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

淺談Webpack 是如何加載模塊的

2019-11-19 13:47:15
字體:
供稿:網(wǎng)友

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)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 汉沽区| 镇安县| 甘泉县| 上高县| 杨浦区| 浦城县| 秦皇岛市| 遵化市| 通州市| 新郑市| 得荣县| 崇阳县| 政和县| 巴林右旗| 南靖县| 黄浦区| 苍南县| 雷波县| 托里县| 元谋县| 通河县| 遵义县| 邢台县| 株洲市| 庆阳市| 桦南县| 芮城县| 滦平县| 乌海市| 仁布县| 新野县| 秦皇岛市| 山阳县| 南靖县| 大方县| 旅游| 上饶县| 修水县| 鸡西市| 濉溪县| 胶州市|