1. 程式人生 > 實用技巧 >淺析常用的import被webpack編譯之後

淺析常用的import被webpack編譯之後

  我們知道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__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"tmpPrint\", function() { return tmpPrint; });\nfunction tmpPrint () {\n  console.log('tmp.js print')\n}\n\n//# 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.\n(' + 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請求,載入模組,模組載入完成以後自動執行其中的程式碼,主要的工作有兩個,更改快取中模組的狀態,另一個就是執行模組程式碼。