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已经执行完毕。

比如如果b返回了字符串"result b", 接下来只有a会被系统执行,且a的loader收到的参数是result b

也就是说pitching loader的初衷是为了提升效率,少执行几个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里执行require(css-loader!resouce), 这会把css-loader跑一遍,也就是说如果按正常顺序执行css-loader会跑两遍(第一遍拿到的js代码用不了), 为了只执行一次,style-loader利用了pitching, 在pitching函数里require(css-loader!resouce)。然后返回js代码(style-loader能够作为最左边loader)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 构建工具逐渐成为前端工程必备的工具,Grunt、Gulp、Fis、Webpack等等,译者有幸使用过Fis、Gul...
    陈坚生阅读 6,195评论 4 64
  • 可以结合慕课网的视频来读这篇文章,地址:http://www.imooc.com/learn/802 Webpac...
    哈哈腾飞阅读 2,100评论 0 7
  • 我现在变得可抠儿!干什么都想省着点,不想让花那么多钱! 现在xx打扮得像个妖怪一样,脸那么白,昨天来我们家我都没认...
    叮咚的你阅读 353评论 3 3
  • 姓名:陈芬 公司:宁波慈星股份有限公司 宁波盛和塾《六项精进》224期学员,利他二组学员 【日精进打卡第196天】...
    龙芬浩阅读 237评论 0 0
  • 晚饭要精打细算,怎样吃的更多更有营养更省钱。看到别人光鲜亮丽,风味小吃,卡布奇诺,大脸鸡排,寿司甚至泡芙都是一种失...
    豪ssman阅读 309评论 0 0

友情链接更多精彩内容