zoukankan      html  css  js  c++  java
  • 浅析常用的import被webpack编译之后

      最近看到一篇文章不错,我们最常用的import来加载模块,但是它真正背后如何运行的,只是略知一二,但真要说出个所以然来,还真不大清楚,所以这篇文章感觉讲的还挺好的,所以转载过来自己学习一下。

      来源于作者李永宁的掘金博客:https://juejin.cn/post/6859569958742196237。

    你的 import 被 webpack 编译成了什么?(李永宁)

    https://juejin.cn/post/6859569958742196237

      我们知道import可以用来加载模块,而且import一般用在需要懒加载的地方。那么你知道 import moduleName from 'xxModule' import('xxModule') 经过webpack编译打包后最终变成了什么?在浏览器中是怎么运行的?

      我们都知道webpack的打包过程大概流程是这样的:

    • 合并webpack.config.js和命令行传递的参数,形成最终的配置
    • 解析配置,得到entry入口
    • 读取入口文件内容,通过@babel/parse将入口内容(code)转换成ast
    • 通过@babel/traverse遍历ast得到模块的各个依赖
    • 通过@babel/core(实际的转换工作是由@babel/preset-env来完成的)将ast转换成es5 code
    • 通过循环伪递归的方式拿到所有模块的所有依赖并都转换成es5

      从以上内容可以看出来,最终的代码中肯定是没有import语句的,因为es5就没有import;那么我们从哪去找答案呢?有两个地方,一是webpack源码,二是打包后的文件,对于今天的问题而言,后者更简单直接一些。

    一、项目体验

    1、/src/index.js

    /**
     * 入口文件,引入 print 方法,并执行
     * 定义了一个 button 方法,为页面添加一个按钮,并为按钮设置了一个 onclick 事件,负责动态引入一个文件
     */
    import { print } from './num.js'
    
    print()
    
    function button () {
      const button = document.createElement('button')
      const text = document.createTextNode('click me')
      button.appendChild(text)
      button.onclick = e => import('./info.js').then(res => {
        console.log(res.log)
      })
      return button
    }
    
    document.body.appendChild(button())

    2、/src/num.js

    import { tmpPrint } from './tmp.js'
    export function print () {
      tmpPrint() 
      console.log('我是 num.js 的 print 方法')
    }

    3、/src/tmp.js

    export function tmpPrint () {
      console.log('tmp.js print')
    }

    4、/src/info.js

    export const log = "log info"

    5、打包

      会看到多了一个 dist 目录,且看输出结果,main.js大家肯定都知道是什么,这个是我们在webpack.config.js中配置的输出的文件名,但是0.main.js呢?这是什么?我们也没配置,可以先想一下,之后我们从代码中找答案

    6、模版文件

      新建/dist/index.html文件,并引入打包后的main.js

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body>
      <script src = "./main.js"></script>
    </body>
    </html>

      在浏览器打开 index.html,可以看到index.html加载以后资源加载以及代码的执行情况,会发现我们写的代码中的同步逻辑均已执行,

      接下来看看异步逻辑(点击按钮),这里为了效果,点击之前分别清空了NetworkConsole两个标签的内容

      点击按钮以后发生了什么?从表面看似乎是这样的:

    点击按钮,在html中动态添加了一个script标签,引入了一个文件(0.main.js),然后发送两个一个http请求进行资源加载,加载成功以后在控制台输出一段日志。

    到这里其实有一部分的答案已经出来,import('xxModule),它提供了一种懒加载的机制,动态往html中添加script`标签,然后加载资源并执行,那具体是怎么做的呢?

      具体内容可以看我之前总结的这篇博客:浅析webpack异步加载原理及分包策略

      好了,现象我们也看完了,接下来我们去源码中找答案。

    二、源码分析

      我们一步一步来拆解打包后的代码。

      首先,我们将打包后的代码进行折叠,如下

    (function (modules) {
      // xxxx
    })({
      // xxx
    })

      这段代码是不是很熟悉?就是一个自执行函数

    1、函数参数

    (function (modules) {
      // xxxx
    })({
        // src/index.js 模块
        "./src/index.js":
          (function (module, __webpack_exports__, __webpack_require__) {
            "use strict";
            __webpack_require__.r(__webpack_exports__);
            var _num_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/num.js");
            Object(_num_js__WEBPACK_IMPORTED_MODULE_0__["print"])()
            function button() {
              const button = document.createElement('button')
              const text = document.createTextNode('click me')
              button.appendChild(text)
              button.onclick = e => __webpack_require__.e(0)
                .then(__webpack_require__.bind(null, "./src/info.js"))
                .then(res => {
                  console.log(res.log)
                })
              return button
            }
            document.body.appendChild(button())
            //# sourceURL=webpack:///./src/index.js?");
          }),
    
        // ./src/num.js 模块
        "./src/num.js":
          (function (module, __webpack_exports__, __webpack_require__) {
            "use strict";
            __webpack_require__.r(__webpack_exports__);
            __webpack_require__.d(__webpack_exports__, "print", function () { return print; });
            var _tmp_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/tmp.js");
            function print() {
              Object(_tmp_js__WEBPACK_IMPORTED_MODULE_0__["tmpPrint"])()
              console.log('我是 num.js 的 print 方法')
            }
            //# sourceURL=webpack:///./src/num.js?");
          }),
    
        // /src/tmp.js 模块
        "./src/tmp.js":
          (function (module, __webpack_exports__, __webpack_require__) {
    
            "use strict";
            // eval("__webpack_require__.r(__webpack_exports__);
    /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tmpPrint", function() { return tmpPrint; });
    function tmpPrint () {
      console.log('tmp.js print')
    }
    
    //# sourceURL=webpack:///./src/tmp.js?");
            __webpack_require__.r(__webpack_exports__);
            __webpack_require__.d(
              __webpack_exports__,
              "tmpPrint",
              function () {
                return tmpPrint;
              });
            function tmpPrint() {
              console.log('tmp.js print')
            }
            //# sourceURL=webpack:///./src/tmp.js?");
          })
    })

      看到这里有没有很熟悉,再回想一下webpack的打包过程,会发现:

      webpack将所有的import moduleName from 'xxModule'都变成了一个Map对象,key为文件路径,value为一个可执行的函数,而函数内容其实就是模块中导出的内容,当然,模块自己也被webpack做了一些处理,接着往下进行。

      从打包后Map对象中能找到我们代码中的各个模块,以及模块的内容,但是也多了很多不属于我们编写的代码,比如以__webpack_require__开头的代码,这些又是什么呢?其实是webpack自定义的一些方法,我们接着往下阅读

    2、函数体

      以下内容为打包后的完整代码,做了一定的格式化,关键地方都写了详细的注释,阅读时搜索“入口位置”开始一步一步的阅读,如果有碰到难以理解的地方可配合单步调试

    /**
     * modules = {
     *  './src/index.js': function () {},
     *  './src/num.js': function () {},
     *  './src/tmp.js': function () {}
     * }
     */
    (function (modules) { // webpackBootstrap
      /**
       * install a JSONP callback for chunk loading
       * 模块加载成功,更改缓存中的模块状态,并且执行模块内容
       * @param {*} data = [
       *  [chunkId],
       *  {
       *    './src/info.js': function () {}
       *  }
       * ]
       */
      function webpackJsonpCallback(data) {
        var chunkIds = data[0];
        var moreModules = data[1];
    
        // add "moreModules" to the modules object,
        // then flag all "chunkIds" as loaded and fire callback
        var moduleId, chunkId, i = 0, resolves = [];
        for (; i < chunkIds.length; i++) {
          chunkId = chunkIds[i];
          if (Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
            resolves.push(installedChunks[chunkId][0]);
          }
          // 这里将模块的加载状态改为了 0,表示加载完成
          installedChunks[chunkId] = 0;
        }
        for (moduleId in moreModules) {
          if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
            // 执行模块代码
            modules[moduleId] = moreModules[moduleId];
          }
        }
        if (parentJsonpFunction) parentJsonpFunction(data);
    
        while (resolves.length) {
          resolves.shift()();
        }
      };
    
      // The module cache, 模块缓存,类似于 commonJS 的 require 缓存机制,只不过这里的 key 是相对路径
      var installedModules = {};
    
      /**
       * 定义 chunk 的加载情况,比如 main = 0 是已加载
       * object to store loaded and loading chunks
       * undefined = chunk not loaded
       * null = chunk preloaded/prefetched
       * Promise = chunk loading
       * 0 = chunk loaded
       */
      var installedChunks = {
        "main": 0
      };
    
      // script path function, 返回需要动态加载的 chunk 的路径
      function jsonpScriptSrc(chunkId) {
        return __webpack_require__.p + "" + chunkId + ".main.js"
      }
    
      /**
       * The require function
       * 接收一个 moduleId,其实就是一个模块相对路径,然后查缓存(没有则添加缓存),
       * 然后执行模块代码,返回模块运行后的 module.exports
       * 一句话总结就是 加载指定模块然后执行,返回执行结果(module.exports)
       * 
       * __webpack_require__(__webpack_require__.s = "./src/index.js")
       */
      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)
         * 
         * // 示例
         * module = installedModules['./src/index.js'] = {
         *  i: './src/index.js',
         *  l: false,
         *  exports: {}
         * }
         */
        var module = installedModules[moduleId] = {
          i: moduleId,
          l: false,
          exports: {}
        };
    
        /**
         * Execute the module function
         * modules['./src/index.js'] is a 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;
      }
    
      // This file contains only the entry chunk.
      // The chunk loading function for additional chunks
      __webpack_require__.e = function requireEnsure(chunkId) {
        var promises = [];
    
        // JSONP chunk loading for javascript
    
        // 从缓存中找该模块
        var installedChunkData = installedChunks[chunkId];
        
        // 0 means "already installed".
        if (installedChunkData !== 0) { 
          
          // 说明模块没有安装
          // a Promise means "currently loading".
          if (installedChunkData) {
            promises.push(installedChunkData[2]);
          } else {
            // setup Promise in chunk cache
            var promise = new Promise(function (resolve, reject) {
              installedChunkData = installedChunks[chunkId] = [resolve, reject];
            });
            promises.push(installedChunkData[2] = promise);
    
            // start chunk loading, create script element
            var script = document.createElement('script');
            var onScriptComplete;
    
            script.charset = 'utf-8';
            // 设置超时时间
            script.timeout = 120;
            if (__webpack_require__.nc) {
              script.setAttribute("nonce", __webpack_require__.nc);
            }
            // script.src = __webpack_public_path__ + chunkId + main.js, 即模块路径
            script.src = jsonpScriptSrc(chunkId);
    
            // create error before stack unwound to get useful stacktrace later
            var error = new Error();
    
            // 加载结果处理函数
            onScriptComplete = function (event) {
              // avoid mem leaks in IE.
              script.onerror = script.onload = null;
              clearTimeout(timeout);
              var chunk = installedChunks[chunkId];
              if (chunk !== 0) {
                // chunk 状态不为 0 ,说明加载出问题了
                if (chunk) {
                  var errorType = event && (event.type === 'load' ? 'missing' : event.type);
                  var realSrc = event && event.target && event.target.src;
                  error.message = 'Loading chunk ' + chunkId + ' failed.
    (' + errorType + ': ' + realSrc + ')';
                  error.name = 'ChunkLoadError';
                  error.type = errorType;
                  error.request = realSrc;
                  chunk[1](error);
                }
                installedChunks[chunkId] = undefined;
              }
            };
            // 超时定时器,超时以后执行
            var timeout = setTimeout(function () {
              onScriptComplete({ type: 'timeout', target: script });
            }, 120000);
            // 加载出错或者加载成功的处理函数
            script.onerror = script.onload = onScriptComplete;
            // 将 script 标签添加到 head 标签尾部
            document.head.appendChild(script);
          }
        }
        return Promise.all(promises);
      };
    
      // expose the modules object (__webpack_modules__)
      __webpack_require__.m = modules;
    
      // expose the module cache
      __webpack_require__.c = installedModules;
    
      /**
       * define getter function for harmony exports
       * @param {*} exports = {}
       * @param {*} name = 模块名
       * @param {*} getter => 模块函数
       * 
       * 在 exports 对象上定义一个 key value,key 为模块名称,value 为模块的可执行函数
       * exports = {
       *  moduleName: module function
       * } 
       */
      __webpack_require__.d = function (exports, name, getter) {
        if (!__webpack_require__.o(exports, name)) {
          Object.defineProperty(exports, name, { enumerable: true, get: getter });
        }
      };
    
      /**
       * define __esModule on exports
       * @param {*} exports = {}
       * 
       * exports = {
       *  __esModule: true
       * }
       */
      __webpack_require__.r = function (exports) {
        if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
          Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
        }
        Object.defineProperty(exports, '__esModule', { value: true });
      };
    
      // create a fake namespace object
      // mode & 1: value is a module id, require it
      // mode & 2: merge all properties of value into the ns
      // mode & 4: return value when already ns object
      // mode & 8|1: behave like require
      __webpack_require__.t = function (value, mode) {
        if (mode & 1) value = __webpack_require__(value);
        if (mode & 8) return value;
        if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
        var ns = Object.create(null);
        __webpack_require__.r(ns);
        Object.defineProperty(ns, 'default', { enumerable: true, value: value });
        if (mode & 2 && typeof value != 'string') for (var key in value) __webpack_require__.d(ns, key, function (key) { return value[key]; }.bind(null, key));
        return ns;
      };
    
      // getDefaultExport function for compatibility with non-harmony modules
      __webpack_require__.n = function (module) {
        var getter = module && module.__esModule ?
          function getDefault() { return module['default']; } :
          function getModuleExports() { return module; };
        __webpack_require__.d(getter, 'a', getter);
        return getter;
      };
    
      // Object.prototype.hasOwnProperty.call
      __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
    
      // __webpack_public_path__
      __webpack_require__.p = "";
    
      // on error function for async loading
      __webpack_require__.oe = function (err) { console.error(err); throw err; };
      
      /**
       * 通过全局属性存储异步加载的资源项,打包文件首次加载时如果属性值不为空,则说明已经有资源被加载了,
       * 将这些资源同步到installedChunks对象中,避免资源重复加载,当然也是这句导致微应用框架single-spa中的所有子应用导出的
       * 包名需要唯一,否则一旦异步的重名模块存在,重名的后续模块不会被加载,且显示的资源是第一个加载的重名模块,
       * 也就是所谓的JS全局作用域的污染
       *
       * 其实上面说的这个问题,webpack官网已经提到了
       * https://webpack.docschina.org/configuration/output/#outputjsonpfunction
       */
      var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || [];
      var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
      jsonpArray.push = webpackJsonpCallback;
      jsonpArray = jsonpArray.slice();
      for (var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
      var parentJsonpFunction = oldJsonpFunction;
    
      /**
       * 入口位置
       * Load entry module and return exports
       */
      return __webpack_require__(__webpack_require__.s = "./src/index.js");
    })
      ({
        // 代码中所有的 import moduleName from 'xxModule' 变成了以下的 Map 对象
    
        // /src/index.js 模块
        "./src/index.js":
          /**
           * @param module = {
           *  i: './src/index.js',
           *  l: false,
           *  exports: {}
           * 
           * @param __webpack_exports__ = module.exports = {}
           * 
           * @param __webpack_require__ => 自定义的 require 函数,加载指定模块,并执行模块代码,返回执行结果
           * 
           */
          (function (module, __webpack_exports__, __webpack_require__) {
            "use strict";
            /**
             * 
             * define __esModule on exports
             * __webpack_exports = module.exports = {
             *  __esModule: true
             * }
             */
            __webpack_require__.r(__webpack_exports__);
            // 加载 ./src/num.js 模块
            var _num_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/num.js");
            Object(_num_js__WEBPACK_IMPORTED_MODULE_0__["print"])()
            function button() {
              const button = document.createElement('button')
              const text = document.createTextNode('click me')
              button.appendChild(text)
              /**
               * 异步执行部分
               */
              button.onclick = e => __webpack_require__.e(0)
                // 模块异步加载完成后,开始执行模块内容 => window["webpackJsonp"].push = window["webpackJsonp"].push = function (data) {}
                .then(__webpack_require__.bind(null, "./src/info.js"))
                .then(res => {
                  console.log(res.log)
                })
              return button
            }
            document.body.appendChild(button())
            //# sourceURL=webpack:///./src/index.js?");
          }),
    
        // /src/num.js 模块
        "./src/num.js":
           /**
           * @param module = {
           *  i: './src/num.js',
           *  l: false,
           *  exports: {}
           * 
           * @param __webpack_exports__ = module.exports = {}
           * 
           * @param __webpack_require__ => 自定义的 require 函数,加载指定模块,并执行模块代码,返回执行结果
           * 
           */
          (function (module, __webpack_exports__, __webpack_require__) {
            "use strict";
             /**
             * 
             * define __esModule on exports
             * __webpack_exports = module.exports = {
             *  __esModule: true
             * }
             */
            __webpack_require__.r(__webpack_exports__);
            /**
             * module.exports = {
             *  __esModule: true,
             *  print
             * }
             */
            __webpack_require__.d(__webpack_exports__, "print", function () { return print; });
            // 加载 ./src/tmp.js 模块
            var _tmp_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("./src/tmp.js");
            function print() {
              Object(_tmp_js__WEBPACK_IMPORTED_MODULE_0__["tmpPrint"])()
              console.log('我是 num.js 的 print 方法')
            }
            //# sourceURL=webpack:///./src/num.js?");
          }),
    
        // /src/tmp.js 模块
        "./src/tmp.js":
          /**
           * @param module = {
           *  i: './src/num.js',
           *  l: false,
           *  exports: {}
           * 
           * @param __webpack_exports__ = module.exports = {}
           * 
           * @param __webpack_require__ => 自定义的 require 函数,加载指定模块,并执行模块代码,返回执行结果
           * 
           */
          (function (module, __webpack_exports__, __webpack_require__) {
    
            "use strict";
             /**
             * 
             * define __esModule on exports
             * __webpack_exports = module.exports = {
             *  __esModule: true
             * }
             */
            __webpack_require__.r(__webpack_exports__);
            /**
             * module.exports = {
             *  __esModule: true,
             *  tmpPrint
             * }
             */
            __webpack_require__.d(__webpack_exports__, "tmpPrint", function () { return tmpPrint; });
            function tmpPrint() {
              console.log('tmp.js print')
            }
            //# sourceURL=webpack:///./src/tmp.js?");
          })
      });

    三、总结

      经过以上内容的学习,相比对于一开始的问题,答案呼之欲出了吧。

      问:import moduleName from 'xxModule'import('xxModule')经过webpack编译打包后最终变成了什么?在浏览器中是怎么运行的?

      答:

    1、import经过webpack打包以后变成一些Map对象,key为模块路径,value为模块的可执行函数;

    2、代码加载到浏览器以后从入口模块开始执行,其中执行的过程中,最重要的就是webpack定义的__webpack_require__函数,负责实际的模块加载并执行这些模块内容,返回执行结果,其实就是读取Map对象,然后执行相应的函数;

    3、当然其中的异步方法(import('xxModule'))比较特殊一些,它会单独打成一个包,采用动态加载的方式

      具体过程:当用户触发其加载的动作时,会动态的在head标签中创建一个script标签,然后发送一个http请求,加载模块,模块加载完成以后自动执行其中的代码,主要的工作有两个,更改缓存中模块的状态,另一个就是执行模块代码。

  • 相关阅读:
    回车换行解释
    二,php的错误处理
    2017年计划
    postgresql无法安装pldbgapi的问题
    在tmux中的vi 上下左右键变为了ABCD等字符
    查看某表有没有语句被锁住
    ubuntu 常见错误--Could not get lock /var/lib/dpkg/lock
    PostgreSQL杀掉死锁的链接
    实现从Oracle增量同步数据到GreenPlum
    终于将rsync-3.1.2配置成功,之外还挖掘了一些新的用法
  • 原文地址:https://www.cnblogs.com/goloving/p/14075523.html
Copyright © 2011-2022 走看看