簡體   English   中英

無法從 webpack 資產庫模塊中解析 css url

[英]Can't resolve css url from webpack asset librarymodule

我能夠 output 一個資產庫和許多其他庫,它們作為遠程聯合模塊和深度導入庫,以防我沒有連接到遠程或者我沒有在消費者端使用 webpack。

現在的問題是我的所有資產都導出了一個模塊,該模塊要么將原始數據作為 uri,要么將字符串指向正確的資產。 例如:bird.svg 與它的 hash 以及解析為文件 bird-[hash].svg 的模塊一起輸出到塵埃。

以上內容來自 javascript,但對於 css 而言則不然。 現在我不能重寫 url() 來指向正確的遠程路徑,就像 sg 一樣:

//since I don't know when the assets will change names I can't refer to it directly. So I would need to first read the string from the bird.js module. Append the publicPath and then rewrite the url. 
.someClass {
  background-image: url('/assets/bird.js')
} 
//the above won't work for obvious reasons. 

所以,問題是我該如何解決這個問題? 或者有沒有為此的加載器? 我檢查了解決 url 加載程序,但似乎不需要。

好的,我通過將附加數據作為變量傳遞給 sass-loader 解決了這個問題。 這樣我就可以評估文件的實際名稱,並將其作為 sass map 之前並從 sass 處理。

//I am using glob to return an object with all the assets.
//This can probably be automated better. That would be an easier way.
//But this way works for me in all 3 scenarios, node, browser and federated module.
//Also has caching ootb for the assets.
const assetsPaths = {
  ...glob.sync('../assets/dist/img/**.node.js').reduce(function (obj, el) {
    obj['img/' + path.parse(el).name] = '../../assets/dist/' + require(el).default;
    return obj
  }, {}), ...glob.sync('../assets/dist/fonts/**.node.js').reduce(function (obj, el) {
    obj['fonts/' + path.parse(el).name] = '../../assets/dist/' + require(el).default;
    return obj
  }, {})
};
//...
{
  loader: 'sass-loader',
  options: {
    additionalData: "$assets: '" + assetsMap + "';",
    sourceMap: true,
    sassOptions: {
      outputStyle: "compressed",
    },
  }
},
//...

您還需要禁用 url 重寫

{
  loader: 'css-loader',
  options: {
    url: false,
  }
},

那么您可以在 sass 文件中使用資產 map :

@font-face { 
  font-family: 'Some Font';
  src: local('Some Font');
  src: url("#{map-get($assets, SomeFont)}");
}

您可能需要將您的項目設置排序為 mono 存儲庫,並且您還需要使用兩個捆綁包構建這些資產庫。

一個用於節點,因此您可以在捆綁 sass/whatever 時使用實際資產的字符串路徑。 另一個用於正常從瀏覽器加載它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM