[英]Webpack Loader with Dynamic Query
我在webpack配置中為SVG文件設置了Webpack加載程序,看起來像這樣
const SVGO_CONFIG = JSON.stringify({
plugins: [
{removeTitle: true},
],
});
const SVG_LOADER = {
test: /\.svg$/,
loader: 'babel!svg-react!svgo?' + SVGO_CONFIG,
};
這使我可以import
svg文件,就像它們是React組件一樣
import Icon from 'src/images/icon.svg';
但是在某些情況下,我希望能夠告訴svgo-loader
從文件中刪除fill
和stroke
屬性。 我可以通過在配置中設置另一個插件來做到這一點
const SVGO_CONFIG = JSON.stringify({
plugins: [
{removeTitle: true},
{removeAttrs: {attrs: "(fill|stroke)"}},
],
});
但這將適用於我導入的所有svg文件。 有沒有簡單的方法來標記導入語句來像這樣稍微修改配置?
import TransparentIcon from 'src/images/icon.svg?removeFill`;
我的半解決方案是使用額外的擴展名(或在其他文件夾中)保存文件,但這意味着無論是否去除屬性,我都無法選擇導入文件。
您可以為此使用include
。 例:
const SVG_LOADER = {
test: /\.svg$/,
loader: 'babel!svg-react!svgo?' + SVGO_CONFIG,
include: [path.join(__dirname, 'svgs/demo.svg', ...]
};
您將需要兩個類似的規則。 您應確保它們的include
不重疊,否則它將同時執行。 解決此問題的一種好方法是將每個目錄的svg分割並指向這些目錄。
有兩種方法:
在兩個單獨的SVG加載器中使用test
屬性的regex,如下所示:
const SVGO_CONFIG = JSON.stringify({ plugins: [ {removeTitle: true}, ], }); const SVG_LOADER = { test: /\\.svg$/, loader: 'babel!svg-react!svgo?' + SVGO_CONFIG, }; const SVGO_CONFIG_REMOVE_FILL = JSON.stringify({ plugins: [ {removeTitle: true}, {removeAttrs: {attrs: "(fill|stroke)"}}, ], }); const SVG_LOADER_REMOVE_FILL = { test: /\\.svg\\?removeFill$/, loader: 'babel!svg-react!svgo?' + SVGO_CONFIG_REMOVE_FILL, };
您可以編寫自己的加載器來調整查詢字符串。 (這可能是過度設計):
module.exports = function(content) { return content; }; module.exports.pitch = function(remainingRequest, precedingRequest, data) { var i; var len = this.loaders.length; var loader; if (this.resourceQuery === '?removeFill') { for (i = 0; i < len; i++) { loader = this.loaders[i]; if (loader.query === '?{"plugins":[{"removeTitle":true}]}') { loader.query = '?' + JSON.stringify({ plugins: [ {removeTitle: true}, {removeAttrs: {attrs: "(fill|stroke)"}}, ], }); } } } };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.