webpack的pitching loader

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, 如果其中任何一個pitching loader返回了值就相當(dāng)于在它以及它右邊的loader已經(jīng)執(zhí)行完畢。

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

也就是說pitching loader的初衷是為了提升效率,少執(zhí)行幾個loader。
然而這樣的機會并不多。更為常用的是它的另一個用途。
根據(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代碼(一個module的代碼,含有類似module.export語句)的loader,還有不能作為最左邊loader的其他loader

問題是有時候我們想把兩個第一種loader chain起來,比如style-loader!css-loader!
問題是css-loader的返回值是一串js代碼,如果按正常方式寫style-loader的參數(shù)就是一串代碼字符串。就算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函數(shù)里require(css-loader!resouce)。然后返回js代碼(style-loader能夠作為最左邊loader)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 構(gòu)建工具逐漸成為前端工程必備的工具,Grunt、Gulp、Fis、Webpack等等,譯者有幸使用過Fis、Gul...
    陳堅生閱讀 6,190評論 4 64
  • 可以結(jié)合慕課網(wǎng)的視頻來讀這篇文章,地址:http://www.imooc.com/learn/802 Webpac...
    哈哈騰飛閱讀 2,096評論 0 7
  • 我現(xiàn)在變得可摳兒!干什么都想省著點,不想讓花那么多錢! 現(xiàn)在xx打扮得像個妖怪一樣,臉那么白,昨天來我們家我都沒認(rèn)...
    叮咚的你閱讀 347評論 3 3
  • 姓名:陳芬 公司:寧波慈星股份有限公司 寧波盛和塾《六項精進》224期學(xué)員,利他二組學(xué)員 【日精進打卡第196天】...
    龍芬浩閱讀 235評論 0 0
  • 晚飯要精打細算,怎樣吃的更多更有營養(yǎng)更省錢??吹絼e人光鮮亮麗,風(fēng)味小吃,卡布奇諾,大臉雞排,壽司甚至泡芙都是一種失...
    豪ssman閱讀 307評論 0 0

友情鏈接更多精彩內(nèi)容