gpt4 book ai didi

webpack - style-loader 如何与 css-loader 一起使用?

转载 作者:行者123 更新时间:2023-12-02 09:07:55 27 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

普通装载机

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

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

请注意,没有俯仰装载机之类的东西,因为每个装载机都可以有“正常侧”和“俯仰侧”。

这是不太有用的webpack doc on pitching loader .最有用的信息是“音高阶段”和“正常阶段”的概念及其执行顺序。

|- 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

你看过 style-loadersource code ,导出看起来像:
module.exports = {}
module.exports.pitch = function loader(request) {
/* ... */
return [/* some string */].join('\n')
}

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

if a loader delivers a result in the pitch method the process turns around and skips the remaining loaders.



目前还不清楚这个音高到底是如何工作的。

深层发掘

我终于遇到了这个 blog post (用中文写)谈到细节。具体来说,它会分析 style-loader 中的确切情况。 pitch方法返回一些东西。

根据博客, pitch方法主要用于在加载器过程的早期访问和修改元数据。从 pitch 返回方法确实很少见,而且文档很少。但是当它确实返回 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

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

如果您检查,此动态生成文件的内容来自 styleLoader.pitch看起来像
var content = require("!!./node_modules/css-loader/dist/cjs.js??ref--8-3!./index.css");

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

结论

基本上,这就是 style-loader做:
  • 它通过暴露 pitch 来提前捕获请求方法。
  • 然后它会理解这个请求是关于什么的,读取所有后续加载器的配置,将所有配置转换为内联查询 require(...)
  • 然后它即时发布一个新文件,通过这样做,原始请求被有效地取消,然后被对该内存文件的新请求替换。

  • 我不知道更好,所有真相都保存在 source codeloader-runner模块。如果有人有更好的引用资料或理解,请发表评论,发布答案或编辑我的。

    关于webpack - style-loader 如何与 css-loader 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55789849/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com