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, 如果其中任何一個(gè)pitching loader返回了值就相當(dāng)于在它以及它右邊的loader已經(jīng)執(zhí)行完畢。
比如如果b返回了字符串"result b", 接下來只有a會(huì)被系統(tǒng)執(zhí)行,且a的loader收到的參數(shù)是result b。
也就是說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語句)的loader,還有不能作為最左邊loader的其他loader
問題是有時(shí)候我們想把兩個(gè)第一種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), 這會(huì)把css-loader跑一遍,也就是說如果按正常順序執(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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
完美解決手機(jī)網(wǎng)頁中輸入框被輸入法遮擋的問題
下面小編就為大家分享一篇完美解決手機(jī)網(wǎng)頁中輸入框被輸入法遮擋的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
JavaScript對(duì)象的創(chuàng)建模式與繼承模式示例講解
繼承機(jī)制是面向?qū)ο蟪绦蛟O(shè)計(jì)使代碼可以復(fù)用的最重要的手段,它允許程序員在保持原有的特性基礎(chǔ)上進(jìn)行擴(kuò)展,增加功能,這樣產(chǎn)生新的類,稱作是派生類。繼承呈現(xiàn)了面向?qū)ο蟪绦蛟O(shè)計(jì)的層析結(jié)構(gòu),體現(xiàn)了由簡(jiǎn)單到復(fù)雜的認(rèn)知過程。繼承是類設(shè)計(jì)層次的復(fù)用2022-12-12
iframe實(shí)現(xiàn)高度自適應(yīng)小程序web-view方案
這篇文章主要為大家介紹了iframe實(shí)現(xiàn)高度自適應(yīng)小程序web-view方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
js實(shí)現(xiàn)隨機(jī)點(diǎn)名小功能
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)隨機(jī)點(diǎn)名小功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
原生js實(shí)現(xiàn)無限循環(huán)輪播圖效果
本文主要介紹了原生js實(shí)現(xiàn)無限循環(huán)輪播圖效果的示例代碼。具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01
js使用i18n實(shí)現(xiàn)頁面國(guó)際化的方法
本篇文章主要介紹了js使用i18n實(shí)現(xiàn)頁面國(guó)際化的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05

