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];
};