先大概了解一下即可

前言

在webpack中,我们在编写代码的时候,可以使用各种各样的模块化,但是最常用的是CommonJSES Module(ES6)。
image.png

CommonJS:node是原生支持的,但是你如果直接放在浏览器上,浏览器是不能识别的; ES Module:有些新的浏览器能识别

Q:这些CommonJSES Module的语法,浏览器是不能识别的。但是,通过webpack打包转化这些模块化的代码后,浏览器就能够识别这些代码了。那么webpack是怎么转化这些模块化的代码,从而使得浏览器能够识别这些模块化的代码呢?

我们来研究一下它的原理,包括如下原理

  • CommonJS模块化实现原理
  • ES Module模块化实现原理
  • CommonJS加载ES Module的原理

    比如,在一个文件中,我用export const num = 1;(ES Module)的方式导出; 然后,在另一个文件中,我用require(‘’)(CommonJS)的方式导入 为什么可以这样呢?就是我们今天需要研究的背后的原理(通过读打包后的源代码)

  • ES Module加载CommonJS的原理

    比如,我现在在webpack中,写了CommonJS的代码,那么经过webpack打包后,浏览器就会识别这些代码了(代码转化)

我们通过打包后的代码来研究这些背后的原理

需要的文件目录如下

image.png
format.js(使用了CommonJS语法)
image.png
math.js(使用了ES Module的语法)
image.png
common_index.js(引入使用CommonJS模块化语法的代码)
image.png
es_index.js(引入使用ES Module模块化语法的代码)
image.png
index.js(混用)
image.png

1)CommonJS模块化实现原理

format.js(使用了CommonJS语法)
image.png
common_index.js(引入使用CommonJS模块化语法的代码)
image.png

通过webpack打包后的代码
说明:由于整体代码立即执行函数包裹,为了方便阅读代码,我们把外面的立即执行函数暂时去掉。

  1. // 定义了一个对象- 模块的路径(key): 函数(value)
  2. var __webpack_modules__ = {
  3. "./src/js/format.js":
  4. (function (module) {
  5. const dateFormat = (date) => {
  6. return "2020-12-12";
  7. }
  8. const priceFormat = (price) => {
  9. return "100.00";
  10. }
  11. // 将我们要导出的变量, 放入到module对象中的exports对象
  12. module.exports = {
  13. dateFormat,
  14. priceFormat
  15. }
  16. })
  17. }
  18. // 定义一个对象, 作为加载模块的缓存
  19. // 该对象是专门用来做“缓存”的。如果我之前加载过一次上面的模块的话,它会把这个加载过的模块
  20. // 放到缓存中,然后下次读取的时候直接从缓存中拿
  21. // 具体缓存过程看下一个_webpack_require_函数!!!
  22. var __webpack_module_cache__ = {};
  23. // 是一个函数, 当我们加载一个模块时, 都会通过这个函数来加载
  24. function __webpack_require__(moduleId) {
  25. // 1.判断缓存中是否已经加载过
  26. if (__webpack_module_cache__[moduleId]) {
  27. return __webpack_module_cache__[moduleId].exports;
  28. }
  29. // 2.给module变量和__webpack_module_cache__[moduleId]赋值了同一个对象
  30. var module = __webpack_module_cache__[moduleId] = { exports: {} };
  31. // 3.加载执行模块
  32. __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  33. // 4.导出module.exports {dateFormat: function, priceForamt: function}
  34. return module.exports;
  35. }
  36. // 立即执行函数,具体开始执行代码逻辑
  37. !function () {
  38. // 1.加载./src/js/format.js
  39. const { dateFormat, priceFormat } = __webpack_require__("./src/js/format.js");
  40. console.log(dateFormat("abc"));
  41. console.log(priceFormat("abc"));
  42. }();

① 定义一个对象

每一个模块都是这么做的(一个对象,key,value分别对应模块路径和函数)

因为我们写的原来的代码中只有一个模块,所以在打包后的代码中该部分只有一个key,value

image.png
image.png

② 定义一个webpack_module_cache对象

③ 定义一个 webpack_require函数

image.png

补充 - 一个对象的连续赋值

④ 具体开始执行代码逻辑

  • 加载 ./src/js/format.js,执行webpack_require函数

image.png

2)ES Module模块实现原理

math.js(使用了ES Module的语法)
image.png
es_index.js(引入使用ES Module模块化语法的代码)
image.png

// 1.定义了一个对象, 对象里面放的是我们的模块映射
var __webpack_modules__ = {
  "./src/es_index.js":
    (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
      // 调用r的目的是记录时一个__esModule -> true
      __webpack_require__.r(__webpack_exports__);

      // _js_math__WEBPACK_IMPORTED_MODULE_0__ == exports
      var _js_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/js/math.js");

      console.log(_js_math__WEBPACK_IMPORTED_MODULE_0__.mul(20, 30));
      console.log(_js_math__WEBPACK_IMPORTED_MODULE_0__.sum(20, 30));
    }),
  "./src/js/math.js":
    (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
      __webpack_require__.r(__webpack_exports__);

      // 调用了d函数: 给exports设置了一个代理definition
      // exports对象中本身是没有对应的函数
      __webpack_require__.d(__webpack_exports__, {
        "sum": function () { return sum; },
        "mul": function () { return mul; }
      });

      const sum = (num1, num2) => {
        return num1 + num2;
      }
      const mul = (num1, num2) => {
        return num1 * num2;
      }
    })
};

// 2.模块的缓存
var __webpack_module_cache__ = {};

// 3.require函数的实现(加载模块)
function __webpack_require__(moduleId) {
  if (__webpack_module_cache__[moduleId]) {
    return __webpack_module_cache__[moduleId].exports;
  }
  var module = __webpack_module_cache__[moduleId] = {
    exports: {}
  };
  __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  return module.exports;
}

!function () {
  // __webpack_require__这个函数对象添加了一个属性: d -> 值function
  __webpack_require__.d = function (exports, definition) {
    for (var key in definition) {
      if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
        Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
      }
    }
  };
}();


!function () {
  // __webpack_require__这个函数对象添加了一个属性: o -> 值function
  __webpack_require__.o = function (obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
}();

!function () {
  // __webpack_require__这个函数对象添加了一个属性: r -> 值function
  __webpack_require__.r = function (exports) {
    if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
      Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
    }
    Object.defineProperty(exports, '__esModule', { value: true });
  };
}();
__webpack_require__("./src/es_index.js");

3) CommonJS和ESModule相互导入

var __webpack_modules__ = ({
  "./src/index.js":
    (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
      "use strict";
      __webpack_require__.r(__webpack_exports__);
      var _js_format__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/js/format.js");
      var _js_format__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_js_format__WEBPACK_IMPORTED_MODULE_0__);

      // es module导出内容, CommonJS导入内容
      const math = __webpack_require__("./src/js/math.js");

      // CommonJS导出内容, es module导入内容
      console.log(math.sum(20, 30));
      console.log(math.mul(20, 30));
      console.log(_js_format__WEBPACK_IMPORTED_MODULE_0___default().dateFormat("aaa"));
      console.log(_js_format__WEBPACK_IMPORTED_MODULE_0___default().priceFormat("bbb"));
    }),
  "./src/js/format.js":
    (function (module) {
      const dateFormat = (date) => {
        return "2020-12-12";
      }
      const priceFormat = (price) => {
        return "100.00";
      }
      module.exports = {
        dateFormat,
        priceFormat
      }
    }),

  "./src/js/math.js":
    (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {

      __webpack_require__.r(__webpack_exports__);
      __webpack_require__.d(__webpack_exports__, {
        "sum": function () { return sum; },
        "mul": function () { return mul; }
      });
      const sum = (num1, num2) => {
        return num1 + num2;
      }

      const mul = (num1, num2) => {
        return num1 * num2;
      }
    })
});

var __webpack_module_cache__ = {};

// The require function
function __webpack_require__(moduleId) {
  // Check if module is in cache
  if (__webpack_module_cache__[moduleId]) {
    return __webpack_module_cache__[moduleId].exports;
  }
  // Create a new module (and put it into the cache)
  var module = __webpack_module_cache__[moduleId] = {
    // no module.id needed
    // no module.loaded needed
    exports: {}
  };

  // Execute the module function
  __webpack_modules__[moduleId](module, module.exports, __webpack_require__);

  // Return the exports of the module
  return module.exports;
}

!function () {
  // getDefaultExport function for compatibility with non-harmony modules
  __webpack_require__.n = function (module) {
    var getter = module && module.__esModule ?
      function () { return module['default']; } :
      function () { return module; };
    __webpack_require__.d(getter, { a: getter });
    return getter;
  };
}();

/* webpack/runtime/define property getters */
!function () {
  // define getter functions for harmony exports
  __webpack_require__.d = function (exports, definition) {
    for (var key in definition) {
      if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
        Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
      }
    }
  };
}();

/* webpack/runtime/hasOwnProperty shorthand */
!function () {
  __webpack_require__.o = function (obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
}();

/* webpack/runtime/make namespace object */
!function () {
  // 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 });
  };
}();

__webpack_require__("./src/index.js");