webpack的pitching loader詳解
webpack中關于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, 正常調用順序應該是c、b、a,但是真正調用順序是
a(pitch)、b(pitch)、c(pitch)、c、b、a, 如果其中任何一個pitching loader返回了值就相當于在它以及它右邊的loader已經執(zhí)行完畢。
比如如果b返回了字符串"result b", 接下來只有a會被系統(tǒng)執(zhí)行,且a的loader收到的參數是result b。
也就是說pitching loader的初衷是為了提升效率,少執(zhí)行幾個loader。
然而這樣的機會并不多。更為常用的是它的另一個用途。
根據官方文檔:
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根據返回值可以分為兩種,一種是返回js代碼(一個module的代碼,含有類似module.export語句)的loader,還有不能作為最左邊loader的其他loader
問題是有時候我們想把兩個第一種loader chain起來,比如style-loader!css-loader!
問題是css-loader的返回值是一串js代碼,如果按正常方式寫style-loader的參數就是一串代碼字符串。就算eval了也不一定拿到什么值
eval('module.export="result";console.log("hello world")') === "hello world"
為了解決這種問題,我們需要在style-loader里執(zhí)行require(css-loader!resouce), 這會把css-loader跑一遍,也就是說如果按正常順序執(zhí)行css-loader會跑兩遍(第一遍拿到的js代碼用不了), 為了只執(zhí)行一次,style-loader利用了pitching, 在pitching函數里require(css-loader!resouce)。然后返回js代碼(style-loader能夠作為最左邊loader)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
javascript中時區(qū)知識的整理UTC GMT問題
這篇文章主要介紹了javascript中時區(qū)知識的整理UTC GMT問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10JS實現的倒計時恢復按鈕點擊功能【可用于協(xié)議閱讀倒計時】
這篇文章主要介紹了JS實現的倒計時恢復按鈕點擊功能,可用于協(xié)議閱讀倒計時,涉及javascript基于setInterval的時間定時觸發(fā)相關操作技巧,需要的朋友可以參考下2018-04-04