.23-淺析webpack源碼之事件流compilation(1)

来源:https://www.cnblogs.com/QH-Jimmy/archive/2018/01/03/8179669.html
-Advertisement-
Play Games

正式開始跑編譯,依次解析,首先是: 流程圖如下: 這裡是第一個compilation事件註入的地方,註入代碼如下: 這裡的requestShortener為FunctionModulePlugin的第二個參數,沒有傳所以是undefined。 options.output為傳入的output參數,但 ...


  正式開始跑編譯,依次解析,首先是:

compiler.apply(
    new JsonpTemplatePlugin(options.output),
    // start
    new FunctionModulePlugin(options.output),
    new NodeSourcePlugin(options.node),
    new LoaderTargetPlugin(options.target)
);

  流程圖如下:

  這裡是第一個compilation事件註入的地方,註入代碼如下:

compiler.plugin("compilation", (compilation) => {
    compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context);
    compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin());
});

  這裡的requestShortener為FunctionModulePlugin的第二個參數,沒有傳所以是undefined。

  options.output為傳入的output參數,但是這裡並沒有用到,而是傳入了compiler.context,如果沒有傳預設為命令執行路徑。

  

RequestShortener

  首先看第一個,源碼簡化如下:

"use strict";

const path = require("path");
// 匹配反斜杠 => \
const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
// 匹配特殊字元
const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
// 匹配正反斜杠 => /\
const SEPARATOR_REGEXP = /[/\\]$/;
// 匹配以'!'開頭或結尾
const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
// 匹配 /index.js
const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
// 將反斜杠替換為正斜杠
const normalizeBackSlashDirection = (request) => {
    return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
};
// 將路徑中特殊字元轉義 例如 - => \-
// 返回一個正則
const createRegExpForPath = (path) => {
    const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&");
    return new RegExp(`(^|!)${regexpTypePartial}`, "g");
};

class RequestShortener {
    constructor(directory) { /**/ }
    shorten(request) { /**/ }
}

module.exports = RequestShortener;

  可以看到都是對路徑做處理,正則都比較簡單,接下來看一下構造函數,其中傳進來的directory為命令執行上下文。

class RequestShortener {
    constructor(directory) {
        // 斜杠轉換
        directory = normalizeBackSlashDirection(directory);
        // 沒看懂啥用
        if (SEPARATOR_REGEXP.test(directory)) directory = directory.substr(0, directory.length - 1);
        // 上下文路徑正則
        // /(^|!)轉義後的路徑/g
        if (directory) {
            this.currentDirectoryRegExp = createRegExpForPath(directory);
        }
        // 返回目錄名
        const dirname = path.dirname(directory);
        // 這裡也不懂幹啥用的
        const endsWithSeperator = SEPARATOR_REGEXP.test(dirname);
        const parentDirectory = endsWithSeperator ? dirname.substr(0, dirname.length - 1) : dirname;
        // 目錄正則
        if (parentDirectory && parentDirectory !== directory) {
            this.parentDirectoryRegExp = createRegExpForPath(parentDirectory);
        }
        // .....\node_modules\webpack\lib
        if (__dirname.length >= 2) {
            // webpack的目錄
            const buildins = normalizeBackSlashDirection(path.join(__dirname, ".."));
            // 目錄檢測
            const buildinsAsModule = this.currentDirectoryRegExp && this.currentDirectoryRegExp.test(buildins);
            // false
            this.buildinsAsModule = buildinsAsModule;
            // 生成webpack目錄路徑正則
            this.buildinsRegExp = createRegExpForPath(buildins);
        }
    }
    shorten(request) { /**/ }
}

  主要是生成了3個目錄匹配正則,上下文、上下文目錄、webpack主目錄三個。

  這裡上下文一般不會是webpack的目錄,所以這個buildingsAsModule理論上都是flase。

  再簡單看一下原型方法shorten:

class RequestShortener {
    constructor(directory) { /**/ }
    shorten(request) {
        if (!request) return request;
        // 轉化路徑斜杠
        request = normalizeBackSlashDirection(request);
        // false
        if (this.buildinsAsModule && this.buildinsRegExp)
            request = request.replace(this.buildinsRegExp, "!(webpack)");
        // 將上下文轉換為!.
        if (this.currentDirectoryRegExp)
            request = request.replace(this.currentDirectoryRegExp, "!.");
        // 將上下文目錄轉換為!..
        if (this.parentDirectoryRegExp)
            request = request.replace(this.parentDirectoryRegExp, "!..");
        // false
        if (!this.buildinsAsModule && this.buildinsRegExp)
            request = request.replace(this.buildinsRegExp, "!(webpack)");
        // 把路徑中的index.js去了 留下參數
        // /index.js?a=1 => ?a=1
        request = request.replace(INDEX_JS_REGEXP, "$1");
        // 把頭尾的!去了
        return request.replace(FRONT_OR_BACK_BANG_REGEXP, "");
    }
}

  可以看出,這個方法將傳入的路徑根據上下文的目錄進行簡化,變成了相對路徑,然後去掉了index.js。

 

FunctionModuleTemplatePlugin

  這個模塊沒有實質性內容,主要是對compilation.moduleTemplate註入事件流,源碼如下:

"use strict";

const ConcatSource = require("webpack-sources").ConcatSource;

class FunctionModuleTemplatePlugin {
    apply(moduleTemplate) {
        moduleTemplate.plugin("render", function(moduleSource, module) { /**/ });
        moduleTemplate.plugin("package", function(moduleSource, module) { /**/ });
        moduleTemplate.plugin("hash", function(hash) { /**/ });
    }
}
module.exports = FunctionModuleTemplatePlugin;

  等觸發的時候再回頭看。

  ConcatSource後面單獨講。

 

  下麵是第二個插件,源碼整理如下:

class NodeSourcePlugin {
    constructor(options) {
        this.options = options;
    }
    apply(compiler) {
        const options = this.options;
        if (options === false) // allow single kill switch to turn off this plugin
            return;

        function getPathToModule(module, type) { /**/ }

        function addExpression(parser, name, module, type, suffix) { /**/ }
        compiler.plugin("compilation", function(compilation, params) {
            params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { /**/ });
        });
        compiler.plugin("after-resolvers", (compiler) => { /**/ });
    }
};

  可以看到,這裡只是簡單判斷了是否關閉了node插件,然後在之前的params參數中的normalModuleFactory屬性上註入了一個parser事件。

 

  第三個插件就更簡單了,如下:

class LoaderTargetPlugin {
    constructor(target) {
        this.target = target;
    }
    apply(compiler) {
        compiler.plugin("compilation", (compilation) => {
            // 這個完全不懂幹啥的
            compilation.plugin("normal-module-loader", (loaderContext) => loaderContext.target = this.target);
        });
    }
}

  這個plugin目前根本看不出來有什麼用。

 

  總之,前三個compilation比較水,沒有什麼內容。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在mysql中,通過一張表的列修改另一張關聯表中的內容: 1: 修改1列 update student s, city c set s.city_name = c.name where s.city_code = c.code; 2: 修改多個列 update a, b set a.title=b. ...
  • 前些天在查看關於innodb_flush_log_at_trx_commit的官網解釋時產生了一些疑問,關於innodb_flush_log_at_trx_commit參數的詳細解釋參見官網: https://dev.mysql.com/doc/refman/5.7/en/innodb-parame ...
  • 一、MyCAT概述 MyCAT是一款由阿裡Cobar演變而來的用於支持資料庫讀寫分離、分片的分散式中間件。MyCAT可不但支持Oracle、MSSQL、MYSQL、PG、DB2關係型資料庫,同時也支持MongoDB等非關係型資料庫。基礎架構如下: 1、MyCAT原理 MyCAT主要是通過對SQL的攔 ...
  • 最近在看高性能MYSQL一書,所以對其進行例子分析已鞏固自己的印象 資料庫的事務操作其實就是一組原子性的操作,要麼全部操作成功,要麼全部操作失敗。 比如說我需要對外銷售1張電影票,且登記一下銷售信息到另一個表,至少需要以下3個步驟 1.查詢電影票數量是否滿足銷售1張電影票 SELECT remain ...
  • 選擇兩個視圖使其等寬高,再去約束裡面就可以設置乘數因數。 簡單的一個例子: 要求:設置白色視圖的寬度為藍色視圖的一半 1、點擊白色視圖連線到父視圖,選擇 Equal Widths 2、選擇右邊第五個模塊 直尺 3、雙擊剛剛添加的寬度約束 4、視圖如下 5、在Multipler里填上0.5 6、Con ...
  • 在runtime.h中,你可以通過其中的一個方法來獲取實例變數,那就是class_copyIvarList方法 ...
  • ...
  • 2017年對我來說註定是不簡單的一個年份,有收穫有遺憾,收穫的是有了人生中第一份工作、在開源世界上有了自己更多的貢獻、閱讀了許多經典的書籍讓自己的知識的深度和廣度上了一個臺階、當然也結識了許多志同道合優秀的朋友、同時趁著自己大學時光的最後一年也出去走走看看;當然遺憾也不少,總感覺時間不夠用,也總感覺... ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...