溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

webpack的pitching loader詳解

發(fā)布時(shí)間:2020-10-13 00:53:24 來(lái)源:腳本之家 閱讀:259 作者:此題無(wú)解灬 欄目:web開(kāi)發(fā)

webpack中關(guān)于pitching loader的文檔比較不清楚:

The loaders are called from right to left. But in some cases loaders do not care about the results of the previous loader or the resource. They only care for metadata. The pitch method on the loaders is called from left to right before the loaders are called. If a loader delivers a result in the pitch method the process turns around and skips the remaining loaders, continuing with the calls to the more left loaders. data can be passed between pitch and normal call.

比如a!b!c!module, 正常調(diào)用順序應(yīng)該是c、b、a,但是真正調(diào)用順序是
a(pitch)、b(pitch)、c(pitch)、c、b、a, 如果其中任何一個(gè)pitching loader返回了值就相當(dāng)于在它以及它右邊的loader已經(jīng)執(zhí)行完畢。

比如如果b返回了字符串"result b", 接下來(lái)只有a會(huì)被系統(tǒng)執(zhí)行,且a的loader收到的參數(shù)是result b。

也就是說(shuō)pitching loader的初衷是為了提升效率,少執(zhí)行幾個(gè)loader。

然而這樣的機(jī)會(huì)并不多。更為常用的是它的另一個(gè)用途。

根據(jù)官方文檔:

In the complex case, when multiple loaders are chained, only the last loader gets the resource file and only the first loader is expected to give back one or two values (JavaScript and SourceMap). Values that any other loader give back are passed to the previous loader.

loader根據(jù)返回值可以分為兩種,一種是返回js代碼(一個(gè)module的代碼,含有類似module.export語(yǔ)句)的loader,還有不能作為最左邊loader的其他loader

問(wèn)題是有時(shí)候我們想把兩個(gè)第一種loader chain起來(lái),比如style-loader!css-loader!

問(wèn)題是css-loader的返回值是一串js代碼,如果按正常方式寫(xiě)style-loader的參數(shù)就是一串代碼字符串。就算eval了也不一定拿到什么值

eval('module.export="result";console.log("hello world")') === "hello world"

為了解決這種問(wèn)題,我們需要在style-loader里執(zhí)行require(css-loader!resouce), 這會(huì)把css-loader跑一遍,也就是說(shuō)如果按正常順序執(zhí)行css-loader會(huì)跑兩遍(第一遍拿到的js代碼用不了), 為了只執(zhí)行一次,style-loader利用了pitching, 在pitching函數(shù)里require(css-loader!resouce)。然后返回js代碼(style-loader能夠作為最左邊loader)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI