最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

webpack DefinePlugin源碼入口解析

 更新時間:2022年11月27日 10:39:23   作者:某時橙  
這篇文章主要為大家介紹了webpack DefinePlugin源碼入口解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

正文

DefinePlugin是webpack的一個官方內(nèi)置插件,它允許在 編譯時 將你代碼中的變量替換為其他值或表達(dá)式。這在需要根據(jù)開發(fā)模式與生產(chǎn)模式進(jìn)行不同的操作時,非常有用。例如,如果想在開發(fā)構(gòu)建中進(jìn)行日志記錄,而不在生產(chǎn)構(gòu)建中進(jìn)行,就可以定義一個全局常量去判斷是否記錄日志。這就是 DefinePlugin 的發(fā)光之處,設(shè)置好它,就可以忘掉開發(fā)環(huán)境和生產(chǎn)環(huán)境的構(gòu)建規(guī)則。

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify('5fa3b9'),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: '1+1',
  'typeof window': JSON.stringify('object'),
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
});

demo

console.log(PRODUCTION,VERSION,BROWSER_SUPPORTS_HTML5,TWO,typeof window,process.env.NODE_ENV);

源碼入口

parser是一個hookMap,它就相當(dāng)于一個管理hook的Map結(jié)構(gòu)。

    apply(compiler) {
        const definitions = this.definitions;
        compiler.hooks.compilation.tap(
            "DefinePlugin",
            (compilation, { normalModuleFactory }) => {
                //...
                normalModuleFactory.hooks.parser
                    .for("javascript/auto")
                    .tap("DefinePlugin", handler);
                normalModuleFactory.hooks.parser
                    .for("javascript/dynamic")
                    .tap("DefinePlugin", handler);
                normalModuleFactory.hooks.parser
                    .for("javascript/esm")
                    .tap("DefinePlugin", handler);                
                //...
            })
    }

parser的call時機在哪?完全就在于NormalModuleFactory.createParser時機

所以這個鉤子的語義就是parser創(chuàng)建時的初始化鉤子。

    createParser(type, parserOptions = {}) {
        parserOptions = mergeGlobalOptions(
            this._globalParserOptions,
            type,
            parserOptions
        );
        const parser = this.hooks.createParser.for(type).call(parserOptions);
        if (!parser) {
            throw new Error(`No parser registered for ${type}`);
        }
        this.hooks.parser.for(type).call(parser, parserOptions);
        return parser;
    }

好,現(xiàn)在讓我們看看具體初始化了什么邏輯。

首先現(xiàn)在program上定義一個鉤子,在遍歷JavaScript AST前(該時機由program定義位置所知),注冊buildInfo.valueDependencies=new Map();

并定義

buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);

const handler = parser => {
                    const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
    //mainValue是在DefinePlugin最初初始化時定義到compilation.valueCacheVersions上的
                    parser.hooks.program.tap("DefinePlugin", () => {
                        const { buildInfo } = parser.state.module;
                        if (!buildInfo.valueDependencies)
                            buildInfo.valueDependencies = new Map();
                        buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
                    });
//....
                    walkDefinitions(definitions, "");
}

然后開始遍歷Definitions(這是用戶提供的配置項,比如 PRODUCTION: JSON.stringify(true),)

            const walkDefinitions = (definitions, prefix) => {
                        Object.keys(definitions).forEach(key => {
                            const code = definitions[key];
                            if (
                                code &&
                                typeof code === "object" &&
                                !(code instanceof RuntimeValue) &&
                                !(code instanceof RegExp)
                            ) {
                            //如果是對象就遞歸調(diào)用
                                walkDefinitions(code, prefix + key + ".");
                                applyObjectDefine(prefix + key, code);
                                return;
                            }
                            applyDefineKey(prefix, key);
                            applyDefine(prefix + key, code);
                        });
                    };

applyDefine

    const applyDefine = (key, code) => {
                        const originalKey = key;
                        const isTypeof = /^typeof\s+/.test(key);
                        if (isTypeof) key = key.replace(/^typeof\s+/, "");
                        let recurse = false;
                        let recurseTypeof = false;
                        if (!isTypeof) {
                            parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
                                addValueDependency(originalKey);
                                return true;
                            });
                            parser.hooks.evaluateIdentifier
                                .for(key)
                                .tap("DefinePlugin", expr => {
                                    /**
                                     * this is needed in case there is a recursion in the DefinePlugin
                                     * to prevent an endless recursion
                                     * e.g.: new DefinePlugin({
                                     * "a": "b",
                                     * "b": "a"
                                     * });
                                     */
                                    if (recurse) return;
                                    addValueDependency(originalKey);
                                    recurse = true;
                                    const res = parser.evaluate(
                                        toCode(
                                            code,
                                            parser,
                                            compilation.valueCacheVersions,
                                            key,
                                            runtimeTemplate,
                                            null
                                        )
                                    );
                                    recurse = false;
                                    res.setRange(expr.range);
                                    return res;
                                });
                            parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
                                addValueDependency(originalKey);
                                const strCode = toCode(
                                    code,
                                    parser,
                                    compilation.valueCacheVersions,
                                    originalKey,
                                    runtimeTemplate,
                                    !parser.isAsiPosition(expr.range[0])
                                );
                                if (/__webpack_require__\s*(!?.)/.test(strCode)) {
                                    return toConstantDependency(parser, strCode, [
                                        RuntimeGlobals.require
                                    ])(expr);
                                } else if (/__webpack_require__/.test(strCode)) {
                                    return toConstantDependency(parser, strCode, [
                                        RuntimeGlobals.requireScope
                                    ])(expr);
                                } else {
                                    return toConstantDependency(parser, strCode)(expr);
                                }
                            });
                        }
                        parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
                            /**
                             * this is needed in case there is a recursion in the DefinePlugin
                             * to prevent an endless recursion
                             * e.g.: new DefinePlugin({
                             * "typeof a": "typeof b",
                             * "typeof b": "typeof a"
                             * });
                             */
                            if (recurseTypeof) return;
                            recurseTypeof = true;
                            addValueDependency(originalKey);
                            const codeCode = toCode(
                                code,
                                parser,
                                compilation.valueCacheVersions,
                                originalKey,
                                runtimeTemplate,
                                null
                            );
                            const typeofCode = isTypeof
                                ? codeCode
                                : "typeof (" + codeCode + ")";
                            const res = parser.evaluate(typeofCode);
                            recurseTypeof = false;
                            res.setRange(expr.range);
                            return res;
                        });
                        parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
                            addValueDependency(originalKey);
                            const codeCode = toCode(
                                code,
                                parser,
                                compilation.valueCacheVersions,
                                originalKey,
                                runtimeTemplate,
                                null
                            );
                            const typeofCode = isTypeof
                                ? codeCode
                                : "typeof (" + codeCode + ")";
                            const res = parser.evaluate(typeofCode);
                            if (!res.isString()) return;
                            return toConstantDependency(
                                parser,
                                JSON.stringify(res.string)
                            ).bind(parser)(expr);
                        });
                    };

hooks.expression

在applyDefine中定義的hooks.expression定義了對表達(dá)式的替換處理。

當(dāng)代碼解析到語句【key】時,便會觸發(fā)如下鉤子邏輯,不過先別急,我們先搞清楚expression鉤子在何處會被觸發(fā)。

parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
//...
                        }

觸發(fā)時機

單單指demo中的情況

比如PRODUCTION會被acron解析為Identifier

而在parse階段中,會有這么一句

        if (this.hooks.program.call(ast, comments) === undefined) {
            //...其他解析語句
            this.walkStatements(ast.body);
        }
//然后會走到這
     walkIdentifier(expression) {
        this.callHooksForName(this.hooks.expression, expression.name, expression);
    }
//最后
        const hook = hookMap.get(name);//獲取hook
        if (hook !== undefined) {
            const result = hook.call(...args); //執(zhí)行hook
            if (result !== undefined) return result;
        }

具體邏輯

    parser.hooks.expression.for(key).tap("DefinePlugin", expr =>{
        addValueDependency(originalKey);
        const strCode = toCode(
            code,
            parser,
            compilation.valueCacheVersions,
            originalKey,
            runtimeTemplate,
            !parser.isAsiPosition(expr.range[0])
        );
        if (/__webpack_require__\s*(!?.)/.test(strCode)) {
            return toConstantDependency(parser, strCode, [
                RuntimeGlobals.require
            ])(expr);
        } else if (/__webpack_require__/.test(strCode)) {
            return toConstantDependency(parser, strCode, [
                RuntimeGlobals.requireScope
            ])(expr);
        } else {
            return toConstantDependency(parser, strCode)(expr);
        }
    });
}

addValueDependency

//這里會影響needBuild的邏輯,是控制是否構(gòu)建模塊的      
const addValueDependency = key => {
                        const { buildInfo } = parser.state.module;
                        //這里就可以理解為設(shè)置key,value
                        buildInfo.valueDependencies.set(
                            VALUE_DEP_PREFIX + key,
                            compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
                        );
                    };

要搞懂a(chǎn)ddValueDependency到底做了什么,首先得理解

  • compilation.valueCacheVersions這個map結(jié)構(gòu)做了什么?
  • buildInfo.valueDependencies這里的依賴收集起來有什么用?

toCode獲取strCode

toConstantDependency

設(shè)置ConstDependency靜態(tài)轉(zhuǎn)換依賴。

exports.toConstantDependency = (parser, value, runtimeRequirements) => {
    return function constDependency(expr) {
        const dep = new ConstDependency(value, expr.range, runtimeRequirements);
        dep.loc = expr.loc;
        parser.state.module.addPresentationalDependency(dep);
        return true;
    };
};

ConstDependency是如何替換源碼的?

出處在seal階段

        if (module.presentationalDependencies !== undefined) {
            for (const dependency of module.presentationalDependencies) {
                this.sourceDependency(
                    module,
                    dependency,
                    initFragments,
                    source,
                    generateContext
                );
            }
        }

sourceDenpendency,會獲取依賴上的執(zhí)行模板

        const constructor = /** @type {new (...args: any[]) => Dependency} */ (
            dependency.constructor
        );
        //template可以理解為代碼生成模板
        const template = generateContext.dependencyTemplates.get(constructor);
///....
template.apply(dependency, source, templateContext);//然后執(zhí)行

而ConstPendency的執(zhí)行模板直接替換了源碼中的某個片段內(nèi)容

const dep = /** @type {ConstDependency} */ (dependency);
        if (dep.runtimeRequirements) {
            for (const req of dep.runtimeRequirements) {
                templateContext.runtimeRequirements.add(req);
            }
        }
        if (typeof dep.range === "number") {
            source.insert(dep.range, dep.expression);
            return;
        }
        source.replace(dep.range[0], dep.range[1] - 1, dep.expression);

hooks.canRename

在applyDefine中,也有hooks.canRename的調(diào)用:

    parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
                            addValueDependency(key);
                            return true;
   });

在這里其實就是允許key可以被重命名,并借機收集key作為依賴,但這個重命名的工作不是替換,并不在definePlugin內(nèi)做,有點點奇怪。

詳細(xì):

該hook會在js ast遍歷時多處被call

  • walkAssignmentExpression 賦值表達(dá)式
  • _walkIIFE CallExpression 函數(shù)調(diào)用表達(dá)式發(fā)現(xiàn)是IIFE時
  • walkVariableDeclaration 聲明語句

canRename有什么用?其實是配合rename使用的鉤子

當(dāng)其返回true,rename鉤子才能起作用。如下:

    walkVariableDeclaration(statement) {
        for (const declarator of statement.declarations) {
            switch (declarator.type) {
                case "VariableDeclarator": {
                    const renameIdentifier =
                        declarator.init && this.getRenameIdentifier(declarator.init);
                    if (renameIdentifier && declarator.id.type === "Identifier") {
                        const hook = this.hooks.canRename.get(renameIdentifier);
                        if (hook !== undefined && hook.call(declarator.init)) {
                            // renaming with "var a = b;"
                            const hook = this.hooks.rename.get(renameIdentifier);
                            if (hook === undefined || !hook.call(declarator.init)) {
                                this.setVariable(declarator.id.name, renameIdentifier);
                            }
                            break;
                        }
                    }
                   //...
                }
            }
        }
    }

官方也有所介紹這個鉤子

hooks.typeof

                        parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
                            addValueDependency(originalKey);
                            const codeCode = toCode(
                                code,
                                parser,
                                compilation.valueCacheVersions,
                                originalKey,
                                runtimeTemplate,
                                null
                            );
                            const typeofCode = isTypeof
                                ? codeCode
                                : "typeof (" + codeCode + ")";
                            const res = parser.evaluate(typeofCode);
                            if (!res.isString()) return;
                            return toConstantDependency(
                                parser,
                                JSON.stringify(res.string)
                            ).bind(parser)(expr);
                        });

先執(zhí)行typeof再用toConstantDependency替換。。

以上就是webpack DefinePlugin源碼入口解析的詳細(xì)內(nèi)容,更多關(guān)于webpack DefinePlugin入口的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • uniapp movable-area應(yīng)用

    uniapp movable-area應(yīng)用

    這篇文章主要為大家介紹了uniapp movable-area應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • JavaScript詞法作用域與調(diào)用對象深入理解

    JavaScript詞法作用域與調(diào)用對象深入理解

    關(guān)于 Javascript 的函數(shù)作用域、調(diào)用對象和閉包之間的關(guān)系很微妙,關(guān)于它們的文章已經(jīng)有很多,本文做了一些總結(jié),需要的朋友可以參考下
    2012-11-11
  • 深入理解關(guān)于javascript中apply()和call()方法的區(qū)別

    深入理解關(guān)于javascript中apply()和call()方法的區(qū)別

    下面小編就為大家?guī)硪黄钊肜斫怅P(guān)于javascript中apply()和call()方法的區(qū)別。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-04-04
  • javascript 動態(tài)腳本添加的簡單方法

    javascript 動態(tài)腳本添加的簡單方法

    下面小編就為大家?guī)硪黄猨avascript 動態(tài)腳本添加的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-10-10
  • js實現(xiàn)移動端圖片滑塊驗證功能

    js實現(xiàn)移動端圖片滑塊驗證功能

    這篇文章主要為大家詳細(xì)介紹了js實現(xiàn)移動端圖片滑塊驗證功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-09-09
  • canvas 畫布在主流瀏覽器中的尺寸限制詳細(xì)介紹

    canvas 畫布在主流瀏覽器中的尺寸限制詳細(xì)介紹

    這篇文章主要介紹了canvas 畫布在主流瀏覽器中的尺寸限制詳細(xì)介紹的相關(guān)資料,canvas在不同瀏覽器下面有不同的最大尺寸限制,這里測試下,需要的朋友可以參考下
    2016-12-12
  • JsonServer安裝及啟動過程圖解

    JsonServer安裝及啟動過程圖解

    這篇文章主要介紹了JsonServer安裝及啟動過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • JavaScript中BOM對象原理與用法分析

    JavaScript中BOM對象原理與用法分析

    這篇文章主要介紹了JavaScript中BOM對象原理與用法,,結(jié)合實例形式分析了javascript中BOM瀏覽器對象模型相關(guān)概念、原理、用法及相關(guān)操作注意事項,需要的朋友可以參考下
    2019-07-07
  • JavaScript實現(xiàn)獲取img的原始尺寸的方法詳解

    JavaScript實現(xiàn)獲取img的原始尺寸的方法詳解

    在微信小程序開發(fā)時,它的image標(biāo)簽有一個默認(rèn)高度,這樣你的圖片很可能出現(xiàn)被壓縮變形的情況,所以就需要獲取到圖片的原始尺寸對image的寬高設(shè)置,本文就來分享一下JavaScript實現(xiàn)獲取img的原始尺寸的方法吧
    2023-03-03
  • js history對象簡單實現(xiàn)返回和前進(jìn)

    js history對象簡單實現(xiàn)返回和前進(jìn)

    返回和前進(jìn)大家應(yīng)該不陌生吧,瀏覽器上面的返回和前進(jìn)按鈕大家瀏覽網(wǎng)頁時都會應(yīng)到的,下面就為大家介紹下js中是如何實現(xiàn)所謂的返回和前進(jìn)
    2013-10-10

最新評論

金溪县| 射洪县| 外汇| 大冶市| 登封市| 西城区| 睢宁县| 深圳市| 柞水县| 友谊县| 杂多县| 哈密市| 托克逊县| 堆龙德庆县| 霍州市| 霍林郭勒市| 老河口市| 筠连县| 高平市| 盐山县| 邯郸市| 酉阳| 昭觉县| 赤城县| 湛江市| 广州市| 惠州市| 钦州市| 筠连县| 东阿县| 广宁县| 南部县| 石台县| 岳池县| 通许县| 桐城市| 电白县| 壤塘县| 盱眙县| 铜鼓县| 铁力市|