webpack 简单的工作原理和输出文件分析

一.webpack 工作流程

webpack 的构建流程可以分为以下三大阶段:

1.初始化:启动构建,读取与合并配置参数,加载 Plugin,实例化 Compiler。
2.编译:从 Entry 发出,针对每个 Module 串行调用对应的 Loader 去翻译文件内容,再找到该 Module 依赖的 Module,递归地进行编译处理。
3.输出:对编译后的 Module 组合成 Chunk,把 Chunk 转换成文件,输出到文件系统。
在开启监听模式下,流程将变为如下:


process.png

在每个阶段中又会发生很多事件,Webpack 会把这些事件广播出来供给 Plugin 使用。


二.webpack 输出文件分析
1.webpack是如何实现module的呢?

我们先创建两个简单的js文件

//index.js,ES6模块
function log(val) {
  console.log(val)
}
export {log}
//main.js  commonjs模块
function helloworld(){
  alert("hello");
}

module.exports =  helloworld

在webpackp配置文件中设置index.js为入口,打包,我们看index.js在打包文件中是什么样子

 (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
    /* harmony export (binding) */ 
__webpack_require__.d(__webpack_exports__, "log", function() { return log; });
function log(val) {
  console.log(val)
}
 })

main.js在打包后

(function(module, exports) {
function helloworld(){
  alert("hello");
}
module.exports =  helloworld
})

可以看到webpack首先将整个文件包裹成模块函数。ES模块会被__webpack_require__.d重新包装成webpack模块。commonjs模块则和webpack模块天然的吻合


2.输出文件分析

这是一个简单的输出的文件,我们主要关注webpack是怎样加载模块的?
bundle.js

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    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;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // 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 = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(1);
module.exports = __webpack_require__(2);


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "log", function() { return log; });
function log(val) {
  console.log(val)
}



/***/ }),
/* 2 */
/***/ (function(module, exports) {

function helloworld(){
  alert("hello");
}

module.exports =  helloworld

/***/ })
/******/ ]);

看起来挺复杂的一个函数,我们简化一下:

(function(modules) {
 //模块缓存,模块第二次被访问时会直接去内存中读取被缓存的返回值
  var installedModules = {};

  // 模拟 require 语句
  function __webpack_require__() {
  }

  // 执行存放所有模块数组中的第0个模块
  __webpack_require__(0);

})([/*存放所有模块的数组*/])

可以看到其实就是用了一个立即执行函数,把模块数组作为参数传进去,在初始化之后,调用入口模块

webpack通过__ webpack_require ____ webpack_exports __来模拟CommonJS规范中的 require和 exports 语句 。但是浏览器不能像 Node.js 那样快速地去本地加载一个个模块文件,而必须通过网络请求去加载还未得到的文件。 如果模块数量很多,加载时间会很长,因此把所有模块都存放在了数组中,执行一次网络加载。


3.代码分割时的输出文件分析

这是抽离的webpack运行文件

/******/ (function(modules) { // webpackBootstrap
/******/    // install a JSONP callback for chunk loading
/******/    var parentJsonpFunction = window["webpackJsonp"];
/******/    window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {
/******/        // add "moreModules" to the modules object,
/******/        // then flag all "chunkIds" as loaded and fire callback
/******/        var moduleId, chunkId, i = 0, resolves = [], result;
/******/        for(;i < chunkIds.length; i++) {
/******/            chunkId = chunkIds[i];
/******/            if(installedChunks[chunkId]) {
/******/                resolves.push(installedChunks[chunkId][0]);
/******/            }
/******/            installedChunks[chunkId] = 0;
/******/        }
/******/        for(moduleId in moreModules) {
/******/            if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/                modules[moduleId] = moreModules[moduleId];
/******/            }
/******/        }
/******/        if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);
/******/        while(resolves.length) {
/******/            resolves.shift()();
/******/        }
/******/        if(executeModules) {
/******/            for(i=0; i < executeModules.length; i++) {
/******/                result = __webpack_require__(__webpack_require__.s = executeModules[i]);
/******/            }
/******/        }
/******/        return result;
/******/    };
/******/
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // objects to store loaded and loading chunks
/******/    var installedChunks = {
/******/        8: 0
/******/    };
/******/
/******/    // The require function
/******/    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;
/******/    }
/******/
/******/    // This file contains only the entry chunk.
/******/    // The chunk loading function for additional chunks
/******/    __webpack_require__.e = function requireEnsure(chunkId) {
/******/        var installedChunkData = installedChunks[chunkId];
/******/        if(installedChunkData === 0) {
/******/            return new Promise(function(resolve) { resolve(); });
/******/        }
/******/
/******/        // a Promise means "currently loading".
/******/        if(installedChunkData) {
/******/            return installedChunkData[2];
/******/        }
/******/
/******/        // setup Promise in chunk cache
/******/        var promise = new Promise(function(resolve, reject) {
/******/            installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/        });
/******/        installedChunkData[2] = promise;
/******/
/******/        // start chunk loading
/******/        var head = document.getElementsByTagName('head')[0];
/******/        var script = document.createElement('script');
/******/        script.type = "text/javascript";
/******/        script.charset = 'utf-8';
/******/        script.async = true;
/******/        script.timeout = 120000;
/******/
/******/        if (__webpack_require__.nc) {
/******/            script.setAttribute("nonce", __webpack_require__.nc);
/******/        }
/******/        script.src = __webpack_require__.p + "static/js/" + chunkId + "." + {"0":"260cd20c695e317fb3c6","1":"d3817d4c70621707136d","2":"3caa0b6145bd20d7a9db","3":"5237fdbb7c4e4f2d59f7","4":"d01831062011a82e2561","5":"29881a369ef38cdc2968"}[chunkId] + ".js";
/******/        var timeout = setTimeout(onScriptComplete, 120000);
/******/        script.onerror = script.onload = onScriptComplete;
/******/        function onScriptComplete() {
/******/            // avoid mem leaks in IE.
/******/            script.onerror = script.onload = null;
/******/            clearTimeout(timeout);
/******/            var chunk = installedChunks[chunkId];
/******/            if(chunk !== 0) {
/******/                if(chunk) {
/******/                    chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));
/******/                }
/******/                installedChunks[chunkId] = undefined;
/******/            }
/******/        };
/******/        head.appendChild(script);
/******/
/******/        return promise;
/******/    };
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // 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; };
/******/ })
/************************************************************************/
/******/ ([]);
//# sourceMappingURL=manifest.e3b60c35149d57ce5744.js.map

和上面所讲的 bundle.js 非常相似,主要区别在于:
多了一个__ webpack_require __.e 用于加载被分割出去的,需要异步加载的Chunk 对应的文件;
多了一个webpackJsonp函数用于从异步加载的 Chunk 文件中安装模块。webpackJsonpCallback先把模块函数存到modules对象中;然后处理chunkIds,调用resolve来改变promise的状态;最后处理executeModules,加载执行executeModules。把 webpackJsonp 挂载到全局是为了方便在其它文件中调用

再来看看其中一个chunk的输出文件

webpackJsonp([7],{

/***/ "+HYV":
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),

/***/ "7K/x":
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),

/***/ "EfXr":
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ }),

/***/ "NHnr":
/***/ (function(module, __webpack_exports__, __webpack_require__) {
 //...

/***/ }),
/***/ "Qbok":
/***/ (function(module, exports) {

// removed by extract-text-webpack-plugin

/***/ })

},["NHnr"]);
//# sourceMappingURL=app.4d89bfb17ddbfc3e25e3.js.map

文件被加载后就会运行这个函数。函数的三个参数分别对应三种模块:
chunkIds 异步加载的文件中存放的需要安装的模块对应的 Chunk ID;
moreModules异步加载的文件中存放的需要安装的模块列表;
executeModules指的是需要立即执行的模块函数的id,对应modules,一般是入口文件对应的模块函数的id。

在使用了 CommonsChunkPlugin 去提取公共代码时输出的文件和使用了异步加载时输出的文件是一样的,都会有 __ webpack_require __.e 和 webpackJsonp。 原因在于提取公共代码和异步加载本质上都是代码分割。


4.回顾

三个主要函数webpackJsonp__ webpack_require____ webpack_require __.e

webpackJsonp也就是webpackJsonpCallback(chunkIds, moreModules, executeModules){…},是bundle文件的包裹函数。

__ webpack_require__(moduleId)通过运行modules里的模块函数来得到模块对象,并保存到installedModules对象中。

__ webpack_require __.e(chunkId)通过建立promise对象来跟踪按需加载模块的加载状态,并设置超时阙值,如果加载超时就抛出js异常。如果不需要处理加载超时异常的话,就不需要这个函数和installedChunks对象,可以把按需加载模块当作普通模块来处理。


参考

原文

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容