Moment For Technology

Source code analysis after Webpack packaging

Posted on Aug. 5, 2023, 9:07 a.m. by Dana Mullen
Category: The front end Tag: webpack

Packaged source code analysis

// /src/index.js
import name from './login'
console.log('index.js=[' + name + '] ')
Copy the code
// /src/login.js
module.exports = "zce"
Copy the code
// dist/built.js
(function (modules) {
  // 01 defines objects for caching loaded modules in the future
  let installedModules = {}

  // 02 Define a __webpack_require__ method to replace the import require load operation
  function __webpack_require__(moduleId) {
    // 2-1 Check whether the current cache contains the contents of the module to be loaded, if so, return directly
    if (installedModules[moduleId]) {
      return installedModules[moduleId].exports
    // 2-2 If the current cache does not exist, we need to define {} to perform the imported module content load
    let module = installedModules[moduleId] = {
      i: moduleId,
      l: false.exports: {}}// 2-3 Call the function corresponding to the current moduleId to load the content
    modules[moduleId].call(module.exports, module.module.exports, __webpack_require__)

    // 2-4 After the above method call is complete, we can change the value of l to indicate that the current module content has been loaded
    module.l = true;

    // 2-5 After the load is complete, the retrieved content is returned to the location of the call
    return module.exports

  // 03 Define the m attribute to store modules
  __webpack_require__.m = modules

  // 04 Define c user save cache catch
  __webpack_require__.c = installedModules

  // 05 Defines the o method to determine whether the specified attribute exists on an object
  __webpack_require__.o = function (object, property) {
    return Object.prototype.hasOwnProperty(object, property)

  // 06 defines the d method to add the specified property to an object and provide a getter for that property
  __webpack_require__.d = function (exports, name, getter) {
    if(! __webpack_require__.o(exports, name)) {
      Object.defineProperty(exports, name, { enumerable: true.get: getter })

  // 07 defines the r method to identify the current module as ES6
  __webpack_require__.r = function(exports) {
    if (typeof Symbol! ='undefined'  Symbol.toStringTag) {
      Object.defineProperty(exports.Symbol.toStringTag, { value: 'Module'})}Object.defineProperty(exports.'__esModule', { value: true})}// 08 defines the n method to set specific getters
  __webpack_require__.n = function(module) {
    let getter = module  modules.__esModule ?
      function getDefault() { return module['default']} :function getmoduleExports() { return module }
    __webpack_require__.d(getter, 'a', getter)

  // 09 Defines the p attribute, which is used to save the resource access path
  __webpack_require__.p = ""

  // Call the __webpack_require__ method to import and load modules
  return __webpack_require__(__webpack_require__.s = './src/index.js') ({})"./src/index.js":
      (function (module, __webpack_exports__, __webpack_require__) {

        "use strict";
        var _login_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/ *! ./login.js */ "./src/login.js");
        console.log('index.js executed ')
        console.log(_login_js__WEBPACK_IMPORTED_MODULE_0__["default"].' -- -- -- -- -- -')
        console.log(_login_js__WEBPACK_IMPORTED_MODULE_0__["age"].' -- -- -- -- -- -')}),"./src/login.js":
      (function (module, __webpack_exports__, __webpack_require__) {
        "use strict";
        __webpack_require__.d(__webpack_exports__, "age".function () { return age; });
        __webpack_exports__["default"] = ('Xiao Ming is a handsome man');
        const age = 40})})Copy the code

How to implement lazy loading

  • Import () HMM allows lazy loading of specified modules
  • The core principle of lazy loading today is thisjsonp
  • tMethods can be processed differently for the content (depending on the values passed in 8, 6, 7, 3, 2, 1)

T method analysis and implementation

// 11 Defines the t method to load the module content of the specified value, process the content and return it
  __webpack_require__.t = function (value, mode) {
    // 01 Loads the contents of the module corresponding to value (value is usually the module ID). The second value mode is a binary value
    // the first thing we do internally is call the custom require method to load the module export corresponding to value.
    // The loaded content is reassigned to the value variable
    // 03 After the value is obtained, the remaining 8, 4 ns 2 are processed to the current content, and then returned to use
    // 04 Return value (commonJS) when mode  8 is set
    // return value to esModule when mode 4 is set
    // if none of the above conditions is true, we still need to process value, define a ns {}
    // 6-1 If the value obtained is something that can be used directly, such as a character toe, mount it to the default property of ns
    // 6-2 If the value is an object, call d to add attributes and getter methods

    if (mode  1) {
      value = __webpack_require__(value)

    if (mode  8) {  // Load content 1 and 8 that can be returned directly
      return value

    if ((mode  4)  typeof value === 'object'  value  value.__esModule) {
      return value

    // If 8 and 4 are not true, you need to define ns to return the content via the default attribute
    let ns = Object.create(null)


    Object.defineProperty(ns, 'default',  { enumerable: true.value: value })

    if (mode  2  typeofvalue ! = ='string') {
      for (var key in value) {
        __webpack_require__.d(ns, key, function (key) {
          return value[key]
        }.bind(null, key))

    return ns
Copy the code

Tapable workflow

  • instantiationhookRegister event Listeners
  • throughhookTrigger event listening
  • Execute executable code generated by lazy compilation

HookNature istapbaleInstance objects

  • HookExecution mechanisms can be classified as synchronous and asynchronous

HookPerform characteristics

  • Hook: Normal hooks. Listeners are independent of each other
  • BailHook: fuses the hook, a listener returns noundefinedIs not executed
  • WaterfallHook: waterfall hook that passes the return value from the last listener to the next
  • LoopHook: Loop hook, if not currently returnedfalseExecute all the way

tapableLibrary sync hook

  • SyncHook
  • SyncBailHook
  • SyncWaterfallHook
  • SyncLoopHook

tapableLibrary asynchronous serial hooks

  • AsyncSeriesHook
  • AsyncSeriesBailHook
  • AsyncSeriesWaterfallHook

tapableLibrary asynchronous parallel hooks

  • AsyncParalleHook
  • AsyncParalleBailHook

Ast Online Debugging

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.