CC 4.0 许可

本节内容源自以下链接的内容,并受 CC BY 4.0 许可证约束。

如果未明确说明,以下内容可被视为基于原始内容进行修改和删除的结果。

内联 matchResource

在请求前缀添加 <match-resource>!=! 将为该请求设置 matchResource

设置 matchResource 后,它将用于与 module.rules 匹配,而不是原始资源。如果需要对资源应用更多加载器,或者需要更改模块类型,这将非常有用。

示例

file.js
/* STYLE: body { background: red; } */
console.log('yep');

加载器可以将文件转换为以下文件,并使用 matchResource 应用用户指定的 CSS 处理规则

file.js (加载器转换后)
import './file.js.css!=!extract-style-loader/getStyles!./file.js';
console.log('yep');

这将添加对 extract-style-loader/getStyles!./file.js 的依赖,并将结果视为 file.js.css。因为 module.rules 有一个与 /\.css$/ 匹配的规则,它将应用于此依赖项。

加载器可能如下所示

extract-style-loader/index.js
const getStylesLoader = require.resolve('./getStyles');

module.exports = function (source) {
  if (STYLES_REGEXP.test(source)) {
    source = source.replace(STYLES_REGEXP, '');
    return `import ${JSON.stringify(
      this.utils.contextify(
        this.context || this.rootContext,
        `${this.resource}.css!=!${getStylesLoader}!${this.remainingRequest}`,
      ),
    )};${source}`;
  }
  return source;
};
extract-style-loader/getStyles.js
module.exports = function (source) {
  const match = source.match(STYLES_REGEXP);
  return match[0];
};