style-loader 如何与 css-loader 配合使用?

Bye*_*oon 6 webpack

我知道 style-loader 通过注入标签将 CSS 添加到 dom 中。并且 css-loader 在遇到 .css 时将 css 作为字符串获取require('./style.css');

但是,style-loader 如何与 css-loader 一起玩?

我正在阅读 style-loader 源代码和 css-loader 源代码。但我无法理解他们是如何一起玩的。

css-loader 从 style.css 中获取的 css 字符串如何传递给 style-loader?

hac*_*ape 10

好问题。为了正确回答这个问题,我做了很多功课。这是我发现的。

普通装载机

webpack loader 的共同理解是,它们是链接起来形成管道的单元。每个加载器处理输入源代码,对其进行转换,然后将结果向下传递到管道中的下一个单元。这个过程一直重复,直到最后一个单元完成它的工作。

但以上只是整个画面的一部分,仅适用于普通加载器style-loader不是普通的loader,因为它也有pitch方法。


pitchLoader的方法

请注意,没有沥青装载机这样的东西,因为每个装载机都可以有“正常侧”和“沥青侧”。

这是关于 Pitching loader的不太有用的webpack 文档。最有用的信息是“音调阶段”和“正常阶段”的概念及其执行顺序。

|- a-loader `pitch`
  |- b-loader `pitch`
    |- c-loader `pitch`
      |- requested module is picked up as a dependency
    |- c-loader normal execution
  |- b-loader normal execution
|- a-loader normal execution
Run Code Online (Sandbox Code Playgroud)

你已经看到了style-loader源代码,导出看起来像:

module.exports = {}
module.exports.pitch = function loader(request) {
  /* ... */
  return [/* some string */].join('\n')
}
Run Code Online (Sandbox Code Playgroud)

文档中与上述源代码唯一相关的部分:

如果加载程序以俯仰方法交付结果,则该过程会转身并跳过剩余的加载程序。

目前还不清楚这个音高究竟是如何运作的。

深层发掘

我终于看到这篇博文(用中文写的)谈论细节。具体而言,分析等的确切情况下style-loader,其中的pitch方法返回的东西。

根据博客,该pitch方法主要用于在加载器过程的早期访问和修改元数据。从pitch方法返回确实很少见,而且记录也很差。但是当它确实返回 sth 以外undefined的东西时,会发生以下情况:

# Normal execution order is disrupted.
|- style-loader `pitch` # <-- because this guy returns string early
# below steps are all canceled out
  |- css-loader `pitch`
    |- requested module is picked up as a dependency
  |- css-loader normal execution
|- style-loader normal execution
Run Code Online (Sandbox Code Playgroud)

然后来自的返回值styleLoader.pitch变成了一个新的内存文件条目。然后像普通文件一样加载此文件,并使用全新的加载过程进行转换。

如果你检查,这个即时生成的文件的内容styleLoader.pitch看起来像

var content = require("!!./node_modules/css-loader/dist/cjs.js??ref--8-3!./index.css");
Run Code Online (Sandbox Code Playgroud)

您会注意到每个require请求都是使用内联查询完全配置的。因此这些请求不会通过任何testin webpackConfig.module.rules.

结论

基本上,这就是style-loader它的作用:

  1. 它通过公开一个pitch方法来尽早捕获请求。
  2. 然后它理解这个请求是关于什么的,读取所有后续加载器的配置,将所有配置转换为内联查询 require(...)
  3. 然后它即时发布一个新文件,通过这样做,原始请求被有效地取消,然后被对这个内存文件的新请求替换

我不知道更好,所有真相都保存在模块的源代码loader-runner。如果有人有更好的参考来源或理解,请发表评论、发布答案或编辑我的。