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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: 首先在编辑器里面插入javascript代码: 确定后会在编辑器插入这样的代码: <pre
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换为SyntaxHighlighter代码高亮插件 上一篇“让kindeditor显示高亮代码”中已经
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高
JS对象如何转为json格式字符串
JS怎么获取图片原始宽高
怎么在click事件中调用多个js函数
js如何往数组中添加新元素
js如何拆分字符串
JS怎么对数组内元素进行求和
JS如何判断屏幕大小
js怎么解析json数据
js如何实时获取浏览器窗口大小
原生JS实现别踩白块小游戏(五)
原生JS实现别踩白块小游戏(一)