Cache bust background images in my CSS with Gulp without having to edit my SASS?

后端 未结 2 810
伪装坚强ぢ
伪装坚强ぢ 2021-02-15 01:09

I want to cache bust background images in my CSS. So if my original style is:

.one {
  background: url(image.png);
}

A string can be added:

2条回答
  •  时光说笑
    2021-02-15 01:51

    The way I see it you have two options - both of which would use the hasher and cache busting plugins you listed:

    1. Write a gulp task that would automatically add ASSET{ ... } around all of the URLs in your CSS file. This would happen after concatenation and before hashing/busting. Since you have a bounty on this question, let me know if you would like me to write that task. I suggest you take a stab at it though b/c you might learn some neat things.

    2. Ideal solution: The cache busting plugin has an option for defining the regex to use to find assets. By default, the regex is set to /ASSET{(.*?)}/g, but you could easily update to something to match good ol' vanilla CSS url(...)s. Again, since you have a bounty let me know if you want help on the regex - but I suggest you take a stab at it b/c you might learn something neat (pssst, you want to ignore data: URLs).

      Try this regex in the cache bust config:
      /url\((?!['"]?data:)['"]?([^'"\)]*)['"]?\)/g

      If you want to ignore URLs which start with "http" (meaning they're hosted on another domain), then use the following regex. This assumes that all paths to your assets are relative, which they should be:
      /url\((?!['"]?(?:data|http):)['"]?([^'"\)]*)['"]?\)/g
      http://www.regexpal.com/?fam=94251

      If you want to be able to define the CSS attributes which will have hashed/busted URLs, you can use the following, which will only apply to URLs defined in background, background-image, and list-style CSS attributes. You can add more by adding a pipe | plus the name of the attribute after |list-style:
      /(?:background(?:-image)?|list-style)[\s]*:[^\r\n;]*url\((?!['"]?(?:data|http):)['"]?([^'"\)]*)/g
      http://www.regexpal.com/?fam=94252

提交回复
热议问题