Stylus inline SVG uri data without base64 encoding

How can I embed SVG data in CSS using the Stylus preprocessor without the Base64 encoded SVG?

Like this:

background: url('data:image/svg+xml;utf8,<svg>[...]</svg>'); 

instead of this:

 background: url('data:image/svg+xml;base64,PD94bWwg[...]'); 

Normaly I used stylus.url() to embed images, but will also encode Base64-encoded SVG.

I want to use uris data instead of external files to save file requests. And I realized that basic SVG encodings actually add bytes instead of downsizing.

I can not find a way to insert SVG as-is.

+6
source share
3 answers

Since I could not find an established way to do this, I had to solve it myself. I wrote a simple node module that wraps stylus.url() , but replaces it as inline SVGs.

Link to the module: https://www.npmjs.com/package/stylus-inline-svg

With the exception of some checks, he basically does this:

 found = stylus.utils.lookup(url.string, options.paths); if(!found) return literal; buf = fs.readFileSync(found); buf = String(buf) .replace(/<\?xml(.+?)\?>/, '') .replace(/^\s+|\s+$/g, '') .replace(/(\r\n|\n|\r)/gm, ''); return new stylus.nodes.Literal("url('data:image/svg+xml;utf8," + buf + "')"); 
+4
source

Stylus now has this functionality built in:

http://stylus-lang.com/docs/functions.url.html

The embedurl function with utf8 support was added to version 0.54.0 on March 5, 2016.

+4
source

Use CSS literal:

 @css { .svg { background: url('data:image/svg+xml;base64,PD94bWwg[...]'); } } 

Compilation:

  .svg { background: url('data:image/svg+xml;base64,PD94bWwg[...]'); } 
0
source

Source: https://habr.com/ru/post/983113/


All Articles