首頁  >  文章  >  web前端  >  深入理解webpack

深入理解webpack

青灯夜游
青灯夜游轉載
2020-07-11 16:46:372082瀏覽

深入理解webpack

webpack是目前最受歡迎的打包工具之一,其配置簡單,功能強大,擁有豐富的載入器和插件系統,為前端開發者提供了許多便利。筆者預設各位看官在閱讀本章之前已經有了一定的使用經驗,所以對webpack的使用方式不做贅述。

閱讀本章,你可以了解以下內容:

  • Webpack打包後程式碼結構
  • Webpack核心架構- Tapable
  • Webpack事件流
  • Webpack外掛程式實作機制
  • Webpack載入器實作機制

Webpack打包後程式碼結構

##簡單打包我們先寫一個最簡單的方法,然後用webpack進行打包:

// /webpack/bundles/simple/moduleA.js
window.printA = function printA() {
    console.log(`This is module A!`);
}
一個比較基本的webpack設定檔:

// /webpack/bundles/simple/webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: {
        main: './moduleA.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'simple.bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ]
}
建立一個HTML檔案用於在瀏覽器環境下測試:

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>Webpack - Simple Bundle</title>


    

執行打包指令

webpack 後我們得到了一個dist 目錄,我們開啟simple.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) {

window.printA = function printA() {
    console.log(`This is module A!`);
}

/***/ })
/******/ ]);
主要看這段:

// ......
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);
// ......
webpack內部定義了一個

webpack_require 的方法,這個方法的實質很簡單:

深入理解webpack

多模組間存在簡單依賴#例如moduleB.js 依賴moduleA.js 檔案。

// /webpack/bundles/simpleDependencies/moduleA.js
module.exports = window.printA = function printA() {
    console.log(`This is module A!`);
}
// /webpack/bundles/simpleDependencies/moduleB.js
const printA = require('./moduleA');

module.exports = window.printB = function printB() {
    printA();
    console.log('This is module B!');
}
將設定檔中的入口更改為

// /webpack/bundles/simpleDependencies/webpack.config.js
// ...
main: './moduleB.js'
// ...
再次打包,我們得到如下程式碼:

// /webpack/bundles/simpleDependencies/dist/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__) {

const printA = __webpack_require__(1);

module.exports = window.printB = function printB() {
    printA();
    console.log('This is module B!');
}

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

module.exports = window.printA = function printA() {
    console.log(`This is module A!`);
}

/***/ })
/******/ ]);
我們可以發現這塊有點變化:

/* 0 */
/***/ (function(module, exports, __webpack_require__) {

const printA = __webpack_require__(1);

module.exports = window.printB = function printB() {
    printA();
    console.log('This is module B!');
}
在moduleB.js 中,需要依賴moduleA ,因而需要先執行__webpack_require(1) 拿到模組A後,再進行下一步。

多重入口需要注意,打包的檔案中moudleId是不會重複的,如果有兩個入口檔案的情況,則入口模組id都為0,其他依賴模組id不重複。我們建立以下幾個文件,其中 index0.js 依賴 common.js 與 dependency.js ,而 index1.js 依賴 index0.js 和 common.js 兩個檔案。

// /webpack/bundles/multi/common.js
module.exports = function() {
    console.log('This is common module!');
}
// /webpack/bundles/multi/dependency .js
module.exports = function() {
    console.log('This is dependency module!');
}
// /webpack/bundles/multi/index0.js
const common = require('./common');
const dependency = require('./dependency');

module.exports = window.print0 = function() {
    common();
    dependency();
    console.log('This is module 0!');
}
// /webpack/bundles/multi/index1.js
const common = require('./common');
const index0 = require('./index0');

module.exports = window.print1 = function() {
    common();
    console.log('This is module 1!');
}
修改webpack.config.js 中的檔案入口:

// /webpack/bundles/multi/webpack.config.js
// ...
entry: {
    index0: './index0.js',
    index1: './index1.js'
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js'
},
// ...
打包後的檔案:

// /webpack/bundles/multi/dist/index0.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 = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

module.exports = function() {
    console.log('This is common module!');
}

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

const common = __webpack_require__(0);
const dependency = __webpack_require__(2);

module.exports = window.print0 = function() {
    common();
    dependency();
    console.log('This is module 0!');
}

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

module.exports = function() {
    console.log('This is dependency module!');
}

/***/ })
/******/ ]);
// /webpack/bundles/multi/dist/index1.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 = 3);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

module.exports = function() {
    console.log('This is common module!');
}

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

const common = __webpack_require__(0);
const dependency = __webpack_require__(2);

module.exports = window.print0 = function() {
    common();
    dependency();
    console.log('This is module 0!');
}

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

module.exports = function() {
    console.log('This is dependency module!');
}

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

const common = __webpack_require__(0);
const index0 = __webpack_require__(1);

module.exports = window.print1 = function() {
    common();
    console.log('This is module 1!');
}

/***/ })
/******/ ]);
顯然,在未使用CommonsChunkPlugin 這個外掛程式之前,這兩個文件是存在重複程式碼的。也就是每個入口都會獨立進行打包。

我們看看如果加入了CommonsChunkPlugin 這個外掛程式後的情況(修改webpack.config.js):

// /webpack/bundles/CommonsChunkPlugin/webpack.config.js
plugins: [
    // ...
    new webpack.optimize.CommonsChunkPlugin({
        name: 'common',
        filename: 'common.js'
    })
]
這樣一來會產生三個文件,index0.bundle.js ,index1.bundel.js以及common.js:

// /webpack/bundles/CommonsChunkPlugin/dist/common.js
/******/ (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 common.js 已經包含了所有的公共方法,並且在瀏覽器window 物件中建立了一個名為webpackJsonp 的方法。 <p></p><pre class="brush:php;toolbar:false">// /webpack/bundles/CommonsChunkPlugin/dist/common.js
// ...
/******/    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 這個方法與 __webpack_require__ 較為類似,同樣也是將模組快取進來。只不過 webpack 會預先抽取公共模組,先將其快取進來,而後可以在其他的 bundle.js 中使用 webpackJsonp 方法進行模組載入。 <p></p><pre class="brush:php;toolbar:false">// /webpack/bundles/CommonsChunkPlugin/dist/index0.bundle.js
webpackJsonp([1],[],[1]);
// /webpack/bundles/CommonsChunkPlugin/dist/index1.bundle.js
webpackJsonp([0],{

/***/ 3:
/***/ (function(module, exports, __webpack_require__) {

const common = __webpack_require__(0);
const index0 = __webpack_require__(1);

module.exports = window.print1 = function() {
    common();
    console.log('This is module 1!');
}

/***/ })

},[3]);

Webpack核心架構- Tapable

#從

github將webpack原始碼複製至本地,我們可以先了解到webpack 的一個整體流程:

深入理解webpack

    lib/webpack.js中傳回一個compiler對象,並呼叫了compiler.run()
  • 在 #lib/Compiler.js中,run方法觸發了before-run、run兩個事件,然後透過readRecords讀取文件,透過compile進行打包,打包後觸發before-compile、compile、make等事件;compile是主要流程,此方法中實例化了一個Compilation類,並呼叫了其finish及seal方法。
  • lib/Compilation.js中定義了finish及seal方法,還有一個重要方法addEntry。這個方法透過呼叫其私有方法_addModuleChain完成了兩件事:根據模組的類型取得對應的模組工廠並建立模組;建構模組。
  • lib/Compiler.js中沒有明確呼叫addEntry,而是觸發make事件,lib/DllEntryPlugin.js為一個監聽make事件的插件,在回調函式中呼叫了addEntry。
具體分析_addModuleChain,其完成的第二件事建構模組又可以分為三部分:

    呼叫loader處理模組之間的依賴。
  • 將loader處理後的檔案透過acorn抽象化成抽象語法樹AST。
  • 遍歷AST,建構該模組的所有依賴。
具體看

lib/webpack.js 這個文件,此文件為 webpack 的入口文件。

const webpack = (options, callback) => {
    const webpackOptionsValidationErrors = validateSchema(
        webpackOptionsSchema,
        options
    );
    if (webpackOptionsValidationErrors.length) {
        throw new WebpackOptionsValidationError(webpackOptionsValidationErrors);
    }
    let compiler;
    if (Array.isArray(options)) {
        compiler = new MultiCompiler(options.map(options => webpack(options)));
    } else if (typeof options === "object") {
        options = new WebpackOptionsDefaulter().process(options);

        compiler = new Compiler(options.context);
        compiler.options = options;
        new NodeEnvironmentPlugin().apply(compiler);
        if (options.plugins && Array.isArray(options.plugins)) {
            for (const plugin of options.plugins) {
                plugin.apply(compiler);
            }
        }
        compiler.hooks.environment.call();
        compiler.hooks.afterEnvironment.call();
        compiler.options = new WebpackOptionsApply().process(options, compiler);
    } else {
        throw new Error("Invalid argument: options");
    }
    if (callback) {
        if (typeof callback !== "function")
            throw new Error("Invalid argument: callback");
        if (
            options.watch === true ||
            (Array.isArray(options) && options.some(o => o.watch))
        ) {
            const watchOptions = Array.isArray(options)
                ? options.map(o => o.watchOptions || {})
                : options.watchOptions || {};
            return compiler.watch(watchOptions, callback);
        }
        compiler.run(callback);
    }
    return compiler;
};

lib/webpack.js 中流程大致如下:

  • 参数验证
  • 创建 Compiler (编译器)对象
  • 注册并执行 NodeEnvironmentPlugin
  • 执行钩子 environment 里的方法
  • 执行钩子 afterEnvironment 里的方法
  • 注册并执行各种插件
  • compiler 向外导出

显然,Compiler是我们需要深究的一个部分,因为 webpack 最终向外部返回也就是这个 Compiler 实例。大致了解下 Compiler 的实现:

class Compiler extends Tapable {
    constructor(context) {
        super();
        this.hooks = {
            // ...
        };
        this._pluginCompat.tap("Compiler", options => {
            // ...
        });
        // ... 
        this.resolvers = {
            normal: {
                // ...
            },
            loader: {
                // ...
            },
            context: {
                // ...
            }
        };
        // ...
    }
    watch(watchOptions, handler) {
        // ...
    }
    run(callback) {
        // ...
    }
    runAsChild(callback) {
        // ...
    }
    purgeInputFileSystem() {
        // ...
    }
    emitAssets(compilation, callback) {
        // ...
    }
    emitRecords(callback) {
        // ...
    }
    readRecords(callback) {
        // ...
    }
    createChildCompiler(
        compilation,
        compilerName,
        compilerIndex,
        outputOptions,
        plugins
    ) {
        // ...
    }
    isChild() {
        // ...
    }
    createCompilation() {
        // ...
    }
    newCompilation(params) {
        // ...
    }
    createNormalModuleFactory() {
        // ...
    }
    createContextModuleFactory() {
        // ...
    }
    newCompilationParams() {
        // ...
    }
    compile(callback) {
        // ...
    }
}

Compiler 继承自 Tapable,在其构造方法中,定义了一些事件钩子(hooks)、一些变量以及一些方法。这些变量以及方法目前看来还是非常抽象的,所以我们有必要去了解下 Tapable 的实现。

Tapable的Github主页 对 Tapable 的介绍如下:

  • The tapable packages exposes many Hook classes, which can be used to create hooks for plugins.

实际上,webpack基于事件流机制,它的工作流程就是将各个插件串联起来,而实现这一切的核心就是Tapable,webpack中最核心的负责编译的Compiler和负责创建bundles的Compilation都是Tapable的实例。Tapable 向外暴露许多的钩子类,这些类可以很方便地为插件创建事件钩子。 Tapable 中定义了如下几种钩子类:

  • SyncHook
  • SyncBailHook
  • SyncWaterfallHook
  • SyncLoopHook
  • AsyncParallelHook
  • AsyncParallelBailHook
  • AsyncSeriesHook
  • AsyncSeriesBailHook
  • AsyncSeriesWaterfallHook

所有钩子类的构造函数都接收一个可选的参数,这个参数是一个由字符串参数组成的数组,如下:

const hook = new SyncHook(["arg1", "arg2", "arg3"]);

钩子概览

Tapable的钩子分为两类,同步和异步,其中异步又分为并行和串行:

深入理解webpack

每种钩子都有各自的使用方式,如下表:

序号 钩子名 执行方式 使用要点
1 SyncHook 同步串行 不关心监听函数的返回值
2 SyncBailHook 同步串行 只要监听函数中有一个函数的返回值不为 null,则跳过剩下所有的逻辑
3 SyncWaterfallHook 同步串行 上一个监听函数的返回值可以传给下一个监听函数
4 SyncLoopHook 同步循环 当监听函数被触发的时候,如果该监听函数返回true时则这个监听函数会反复执行,如果返回 undefined 则表示退出循环
5 AsyncParallelHook 异步并发 不关心监听函数的返回值
6 AsyncParallelBailHook 异步并发 只要监听函数的返回值不为 null,就会忽略后面的监听函数执行,直接跳跃到callAsync等触发函数绑定的回调函数,然后执行这个被绑定的回调函数
7 AsyncSeriesHook 异步串行 不关系callback()的参数
8 AsyncSeriesBailHook 异步串行 callback()的参数不为null,就会直接执行callAsync等触发函数绑定的回调函数
9 AsyncSeriesWaterfallHook 异步串行 上一个监听函数的中的callback(err, data)的第二个参数,可以作为下一个监听函数的参数

Sync钩子

同步串行
(1) SyncHook
不关心监听函数的返回值

  • 使用
const { SyncHook } = require("tapable");
let queue = new SyncHook(['name']); //所有的构造函数都接收一个可选的参数,这个参数是一个字符串的数组。

// 订阅
queue.tap('1', function (name, name2) {// tap 的第一个参数是用来标识订阅的函数的
    console.log(name, name2, 1);
    return '1'
});
queue.tap('2', function (name) {
    console.log(name, 2);
});
queue.tap('3', function (name) {
    console.log(name, 3);
});

// 发布
queue.call('webpack', 'webpack-cli');// 发布的时候触发订阅的函数 同时传入参数

// 执行结果:
/*
webpack undefined 1 // 传入的参数需要和new实例的时候保持一致,否则获取不到多传的参数
webpack 2
webpack 3
*/
  • 原理
class SyncHook_MY{
    constructor(){
        this.hooks = [];
    }

    // 订阅
    tap(name, fn){
        this.hooks.push(fn);
    }

    // 发布
    call(){
        this.hooks.forEach(hook => hook(...arguments));
    }
}

(2) SyncBailHook
只要监听函数中有一个函数的返回值不为 null,则跳过剩下所有的逻辑

  • 使用
const {
    SyncBailHook
} = require("tapable");

let queue = new SyncBailHook(['name']); 

queue.tap('1', function (name) {
    console.log(name, 1);
});
queue.tap('2', function (name) {
    console.log(name, 2);
    return 'wrong'
});
queue.tap('3', function (name) {
    console.log(name, 3);
});

queue.call('webpack');

// 执行结果:
/* 
webpack 1
webpack 2
*/
  • 原理
class SyncBailHook_MY {
    constructor() {
        this.hooks = [];
    }

    // 订阅
    tap(name, fn) {
        this.hooks.push(fn);
    }

    // 发布
    call() {
        for (let i = 0, l = this.hooks.length; i <p>(3) SyncWaterfallHook<br>上一个监听函数的返回值可以传给下一个监听函数</p>
  • 使用
const {
    SyncWaterfallHook
} = require("tapable");

let queue = new SyncWaterfallHook(['name']);

// 上一个函数的返回值可以传给下一个函数
queue.tap('1', function (name) {
    console.log(name, 1);
    return 1;
});
queue.tap('2', function (data) {
    console.log(data, 2);
    return 2;
});
queue.tap('3', function (data) {
    console.log(data, 3);
});

queue.call('webpack');

// 执行结果:
/* 
webpack 1
1 2
2 3
*/
  • 原理
class SyncWaterfallHook_MY{
    constructor(){
        this.hooks = [];
    }
    
    // 订阅
    tap(name, fn){
        this.hooks.push(fn);
    }

    // 发布
    call(){
        let result = null;
        for(let i = 0, l = this.hooks.length; i <p>(4) SyncLoopHook<br>当监听函数被触发的时候,如果该监听函数返回true时则这个监听函数会反复执行,如果返回 undefined 则表示退出循环。</p>
  • 使用
const {
    SyncLoopHook
} = require("tapable");

let queue = new SyncLoopHook(['name']); 

let count = 3;
queue.tap('1', function (name) {
    console.log('count: ', count--);
    if (count > 0) {
        return true;
    }
    return;
});

queue.call('webpack');

// 执行结果:
/* 
count:  3
count:  2
count:  1
*/
  • 原理
class SyncLoopHook_MY {
    constructor() {
        this.hook = null;
    }

    // 订阅
    tap(name, fn) {
        this.hook = fn;
    }

    // 发布
    call() {
        let result;
        do {
            result = this.hook(...arguments);
        } while (result)
    }
}

Async钩子

异步并行
(1) AsyncParallelHook
不关心监听函数的返回值。有三种注册/发布的模式,如下:

异步订阅 调用方法
tap callAsync
tapAsync callAsync
tapPromise promise
  • usage - tap
const {
    AsyncParallelHook
} = require("tapable");

let queue1 = new AsyncParallelHook(['name']);
console.time('cost');
queue1.tap('1', function (name) {
    console.log(name, 1);
});
queue1.tap('2', function (name) {
    console.log(name, 2);
});
queue1.tap('3', function (name) {
    console.log(name, 3);
});
queue1.callAsync('webpack', err => {
    console.timeEnd('cost');
});

// 执行结果
/* 
webpack 1
webpack 2
webpack 3
cost: 4.520ms
*/
  • usage - tapAsync
let queue2 = new AsyncParallelHook(['name']);
console.time('cost1');
queue2.tapAsync('1', function (name, cb) {
    setTimeout(() => {
        console.log(name, 1);
        cb();
    }, 1000);
});
queue2.tapAsync('2', function (name, cb) {
    setTimeout(() => {
        console.log(name, 2);
        cb();
    }, 2000);
});
queue2.tapAsync('3', function (name, cb) {
    setTimeout(() => {
        console.log(name, 3);
        cb();
    }, 3000);
});

queue2.callAsync('webpack', () => {
    console.log('over');
    console.timeEnd('cost1');
});

// 执行结果
/* 
webpack 1
webpack 2
webpack 3
over
time: 3004.411ms
*/
  • usage - promise
let queue3 = new AsyncParallelHook(['name']);
console.time('cost3');
queue3.tapPromise('1', function (name, cb) {
   return new Promise(function (resolve, reject) {
       setTimeout(() => {
           console.log(name, 1);
           resolve();
       }, 1000);
   });
});

queue3.tapPromise('1', function (name, cb) {
   return new Promise(function (resolve, reject) {
       setTimeout(() => {
           console.log(name, 2);
           resolve();
       }, 2000);
   });
});

queue3.tapPromise('1', function (name, cb) {
   return new Promise(function (resolve, reject) {
       setTimeout(() => {
           console.log(name, 3);
           resolve();
       }, 3000);
   });
});

queue3.promise('webpack')
   .then(() => {
       console.log('over');
       console.timeEnd('cost3');
   }, () => {
       console.log('error');
       console.timeEnd('cost3');
   });
/* 
webpack 1
webpack 2
webpack 3
over
cost3: 3007.925ms
*/

异步串行
(1) AsyncSeriesHook
不关心callback()的参数。

  • usage - tap
const {
    AsyncSeriesHook
} = require("tapable");

// tap
let queue1 = new AsyncSeriesHook(['name']);
console.time('cost1');
queue1.tap('1', function (name) {
    console.log(1);
    return "Wrong";
});
queue1.tap('2', function (name) {
    console.log(2);
});
queue1.tap('3', function (name) {
    console.log(3);
});
queue1.callAsync('zfpx', err => {
    console.log(err);
    console.timeEnd('cost1');
});
// 执行结果
/* 
1
2
3
undefined
cost1: 3.933ms
*/
  • usage - tapAsync
let queue2 = new AsyncSeriesHook(['name']);
console.time('cost2');
queue2.tapAsync('1', function (name, cb) {
    setTimeout(() => {
        console.log(name, 1);
        cb();
    }, 1000);
});
queue2.tapAsync('2', function (name, cb) {
    setTimeout(() => {
        console.log(name, 2);
        cb();
    }, 2000);
});
queue2.tapAsync('3', function (name, cb) {
    setTimeout(() => {
        console.log(name, 3);
        cb();
    }, 3000);
});

queue2.callAsync('webpack', (err) => {
    console.log(err);
    console.log('over');
    console.timeEnd('cost2');
}); 
// 执行结果
/* 
webpack 1
webpack 2
webpack 3
undefined
over
cost2: 6019.621ms
*/
  • usage - promise
let queue3 = new AsyncSeriesHook(['name']);
console.time('cost3');
queue3.tapPromise('1',function(name){
   return new Promise(function(resolve){
       setTimeout(function(){
           console.log(name, 1);
           resolve();
       },1000)
   });
});
queue3.tapPromise('2',function(name,callback){
    return new Promise(function(resolve){
        setTimeout(function(){
            console.log(name, 2);
            resolve();
        },2000)
    });
});
queue3.tapPromise('3',function(name,callback){
    return new Promise(function(resolve){
        setTimeout(function(){
            console.log(name, 3);
            resolve();
        },3000)
    });
});
queue3.promise('webapck').then(err=>{
    console.log(err);
    console.timeEnd('cost3');
});

// 执行结果
/* 
webapck 1
webapck 2
webapck 3
undefined
cost3: 6021.817ms
*/
  • 原理
class AsyncSeriesHook_MY {
    constructor() {
        this.hooks = [];
    }

    tapAsync(name, fn) {
        this.hooks.push(fn);
    }

    callAsync() {
        var slef = this;
        var args = Array.from(arguments);
        let done = args.pop();
        let idx = 0;

        function next(err) {
            // 如果next的参数有值,就直接跳跃到 执行callAsync的回调函数
            if (err) return done(err);
            let fn = slef.hooks[idx++];
            fn ? fn(...args, next) : done();
        }
        next();
    }
}

(2) AsyncSeriesBailHook
callback()的参数不为null,就会直接执行callAsync等触发函数绑定的回调函数。

  • usage - tap
const {
    AsyncSeriesBailHook
} = require("tapable");

// tap
let queue1 = new AsyncSeriesBailHook(['name']);
console.time('cost1');
queue1.tap('1', function (name) {
    console.log(1);
    return "Wrong";
});
queue1.tap('2', function (name) {
    console.log(2);
});
queue1.tap('3', function (name) {
    console.log(3);
});
queue1.callAsync('webpack', err => {
    console.log(err);
    console.timeEnd('cost1');
});

// 执行结果:
/* 
1
null
cost1: 3.979ms
*/
  • usage - tapAsync
let queue2 = new AsyncSeriesBailHook(['name']);
console.time('cost2');
queue2.tapAsync('1', function (name, callback) {
    setTimeout(function () {
        console.log(name, 1);
        callback();
    }, 1000)
});
queue2.tapAsync('2', function (name, callback) {
    setTimeout(function () {
        console.log(name, 2);
        callback('wrong');
    }, 2000)
});
queue2.tapAsync('3', function (name, callback) {
    setTimeout(function () {
        console.log(name, 3);
        callback();
    }, 3000)
});
queue2.callAsync('webpack', err => {
    console.log(err);
    console.log('over');
    console.timeEnd('cost2');
});
// 执行结果

/* 
webpack 1
webpack 2
wrong
over
cost2: 3014.616ms
*/
  • usage - promise
let queue3 = new AsyncSeriesBailHook(['name']);
console.time('cost3');
queue3.tapPromise('1', function (name) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(name, 1);
            resolve();
        }, 1000)
    });
});
queue3.tapPromise('2', function (name, callback) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(name, 2);
            reject();
        }, 2000)
    });
});
queue3.tapPromise('3', function (name, callback) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            console.log(name, 3);
            resolve();
        }, 3000)
    });
});
queue3.promise('webpack').then(err => {
    console.log(err);
    console.log('over');
    console.timeEnd('cost3');
}, err => {
    console.log(err);
    console.log('error');
    console.timeEnd('cost3');
});
// 执行结果:
/* 
webpack 1
webpack 2
undefined
error
cost3: 3017.608ms
*/

(3) AsyncSeriesWaterfallHook
上一个监听函数的中的callback(err, data)的第二个参数,可以作为下一个监听函数的参数

  • usage - tap
const {
    AsyncSeriesWaterfallHook
} = require("tapable");

// tap
let queue1 = new AsyncSeriesWaterfallHook(['name']);
console.time('cost1');
queue1.tap('1', function (name) {
    console.log(name, 1);
    return 'lily'
});
queue1.tap('2', function (data) {
    console.log(2, data);
    return 'Tom';
});
queue1.tap('3', function (data) {
    console.log(3, data);
});
queue1.callAsync('webpack', err => {
    console.log(err);
    console.log('over');
    console.timeEnd('cost1');
});

// 执行结果:
/* 
webpack 1
2 'lily'
3 'Tom'
null
over
cost1: 5.525ms
*/
  • usage - tapAsync
let queue2 = new AsyncSeriesWaterfallHook(['name']);
console.time('cost2');
queue2.tapAsync('1', function (name, callback) {
    setTimeout(function () {
        console.log('1: ', name);
        callback(null, 2);
    }, 1000)
});
queue2.tapAsync('2', function (data, callback) {
    setTimeout(function () {
        console.log('2: ', data);
        callback(null, 3);
    }, 2000)
});
queue2.tapAsync('3', function (data, callback) {
    setTimeout(function () {
        console.log('3: ', data);
        callback(null, 3);
    }, 3000)
});
queue2.callAsync('webpack', err => {
    console.log(err);
    console.log('over');
    console.timeEnd('cost2');
});
// 执行结果:
/* 
1:  webpack
2:  2
3:  3
null
over
cost2: 6016.889ms
*/
  • usage - promise
let queue3 = new AsyncSeriesWaterfallHook(['name']);
console.time('cost3');
queue3.tapPromise('1', function (name) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log('1:', name);
            resolve('1');
        }, 1000)
    });
});
queue3.tapPromise('2', function (data, callback) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            console.log('2:', data);
            resolve('2');
        }, 2000)
    });
});
queue3.tapPromise('3', function (data, callback) {
    return new Promise(function (resolve) {
        setTimeout(function () {
            console.log('3:', data);
            resolve('over');
        }, 3000)
    });
});
queue3.promise('webpack').then(err => {
    console.log(err);
    console.timeEnd('cost3');
}, err => {
    console.log(err);
    console.timeEnd('cost3');
});
// 执行结果:
/* 
1: webpack
2: 1
3: 2
over
cost3: 6016.703ms
*/
  • 原理
class AsyncSeriesWaterfallHook_MY {
    constructor() {
        this.hooks = [];
    }

    tapAsync(name, fn) {
        this.hooks.push(fn);
    }

    callAsync() {
        let self = this;
        var args = Array.from(arguments);

        let done = args.pop();
        console.log(args);
        let idx = 0;
        let result = null;

        function next(err, data) {
            if (idx >= self.hooks.length) return done();
            if (err) {
                return done(err);
            }
            let fn = self.hooks[idx++];
            if (idx == 1) {

                fn(...args, next);
            } else {
                fn(data, next);
            }
        }
        next();
    }
}

Tapable事件流

webpack中的事件归纳如下,这些事件出现的顺序固定,但不一定每次打包所有事件都触发:

##[A]applyPlugins環境[A]applyPlugins後環境##[ D ]#[A]##[A]applyPluginscontext-module-factory[A]applyPlugins compile[A]applyPluginsthis-compilation [A]applyPlugins編譯#[F]applyPluginsParallelmake [E]applyPluginsAsyncWaterfall解析前applyPluginsWaterfallapplyPluginsWaterfall# #[A] applyPluginsresolve#[A]applyPluginsresolve-step檔案##[G]#applyPluginsParallelBailResult # #目錄[A]applyPluginsresolve-step## applyPluginsWaterfallmodule[A]applyPluginsbuild-module正常模組載入器程式語句[C][C][C][C][C]##[C]applyPluginsBailResult評估文字[C]applyPluginsBailResultcall require:amd:array#[C]applyPluginsBailResult評估文字[C]applyPluginsBailResultcall require :commonjs:item[C]applyPluginsBailResult語句 [C]applyPluginsBailResultevaluate MemberExpressionapplyPluginsBailResult[C]applyPluginsBailResultcall console.log##[C][C][A][E][B][A ]#[A][A][A][A][ A] [A][A]##[D]applyPluginsAsyncSeriesoptimize-tree[A]applyPlugins#after-optimize-tree[C]applyPluginsBailResult#應該要記錄 applyPlugins#applyPluginsapplyPluginsapplyPlugins#applyPluginsapplyPluginsapplyPluginsapplyPluginsapplyPluginsapplyPluginsapplyPluginsapplyPlugins##[A]applyPlugins#before-chunk-assets[B]applyPluginsWaterfallglobal-hash-paths[C]applyPluginsBailResultglobal-hash[B]applyPluginsWaterfallbootstrap[B]applyPluginsWaterfalllocal-vars[B]applyPluginsWaterfallrequire[B] applyPluginsWaterfallmodule-obj[B]applyPluginsWaterfallmodule-require[B]applyPluginsWaterfall#require-extensions##[B][B] [B ][B]#[B][B][B]##[B] applyPluginsWaterfall模組#[B]applyPluginsWaterfallapplyPluginsWaterfallapplyPluginsWaterfallapplyPluginsWaterfall##[B]applyPluginsWaterfall資產路徑#[B]applyPluginsWaterfall##資產路徑chunk-asset附加區塊資產record# #[D]applyPluginsAsyncSeries附加資產[D]applyPluginsAsyncSeries#optimize- chunk-assets[A]applyPluginsafter-optimize-chunk-assets [D]applyPluginsAsyncSeriesoptimize-assets[A]applyPlugins#優化後-assets#[D]applyPluginsAsyncSeries#編譯後[C]applyPluginsBailResult#should-emit[D]applyPluginsAsyncSeriesemit[B]applyPluginsWaterfall資產路徑#[D]applyPluginsAsyncSeries#after-emit[A]applyPluginsdoneentry-option:初始化選項run:開始編譯
類型 名稱 事件名稱
[C] applyPluginsBailResult entry-option
[A] applyPlugins #after-plugins
#[A] applyPlugins 後解析器
applyPluginsAsyncSeries run
applyPlugins 正常模組工廠
##[B]
工廠 [B]
解析器
##[G] applyPluginsParallelBailResult
## [G] applyPluginsParallelBailResult 結果
[E] applyPluginsAsyncWaterfall 解析後
[C] applyPluginsBailResult create-module
[B] applyPluginsWaterfall [B]
# #[A] applyPlugins
#[C] applyPluginsBailResult
[C] applyPluginsBailResult
[C] applyPluginsBailResult
applyPluginsBailResult evaluate CallExpression
applyPluginsBailResult var data
applyPluginsBailResult 評估識別碼
applyPluginsBailResult #評估識別碼require
applyPluginsBailResult #call require
##[C]
evaluate Identifier 控制台。log #evaluate Identifier 控制台。 log evaluate
applyPluginsBailResult 表達式控制台.log
applyPluginsBailResult ##表達式控制台
applyPlugins succeed-module
applyPluginsAsyncWaterfall 解析前
applyPluginsWaterfall factory
applyPlugins build-module
applyPlugins succeed-module
applyPlugins seal
applyPlugins optimize
applyPlugins optimize-modules
applyPlugins after-optimize-modules
applyPlugins #optimize- chunks
applyPlugins #after-optimize-chunks
##[A]
revive-modules [A]
optimize-module-order #[A]
before-module-ids [A]
optimize-module-ids [A]
after-optimize-module-ids [A]
record-modules [A]
# revive-chunks [A]
optimize-chunk-order [A ]
before-chunk-ids [A]
# optimize-chunk -ids [A]
after-optimize-chunk-ids [ A]
記錄區塊
[A] applyPlugins before-hash
[A] applyPlugins hash
[A] applyPlugins hash-for-chunk
[ A] applyPlugins chunk-hash
#[A] applyPlugins after-hash
#applyPluginsWaterfall 資產路徑
applyPluginsWaterfall startup
applyPluginsWaterfall module-require
applyPluginsWaterfall 渲染
applyPluginsWaterfall #模組
applyPluginsWaterfall render
applyPluginsWaterfall package
##render [B]
套件 [B]
模組 [B]
render-with-entry
#[A] applyPlugins
[A] applyPlugins
[A] applyPlugins
#幾個關鍵的事件對應的階段:

make:從entry開始遞歸分析依賴檔案依賴進行build

    build- moodule:使用loader載入檔案並build模組
  • normal-module-loader:對loder載入的檔案用acorn編譯,產生抽象語法樹AST
  • program:開始對AST進行檢索,當遇到require時觸發call require事件
  • seal:所有依賴構建完成,開始對chunk進行優化(抽取公共模組、加哈希等)
  • optimize-chunk-assets :壓縮程式碼
  • emit:把各個區塊輸出到結果檔案
  • 了解以上事件,你可以很容易地寫出一個外掛程式。
  • ...未完成待續
  • #引用

##Webpack-原始碼二,整體呼叫與Tapable事件流

webpack4.0源碼分析之Tapable
  • ##相關教學推薦:《
  • Web pack入門影片教學

以上是深入理解webpack的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jianshu.com。如有侵權,請聯絡admin@php.cn刪除