Stylus inline SVG data uri without base64 encoding
Asked Answered
R

3

7

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

Like this:

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

instead of this:

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

Normaly I've used stylus.url() to embed images, but it will also Base64 encode SVGs.

I want to use data uris instead of external files to save file requests. And I've realised that Base64 encoding SVGs actually adds bytes instead of reducing size.

I can't find a method to embed the SVG as-is.

Renata answered 27/2, 2015 at 16:17 Comment(3)
You can't do an externat .svg file and call it in css ? Like background: url(youshape.svg);Smitt
Also, background images (even SVG) are not "inline images".Autolycus
@Autolycus I'm used to SASS and Compass where the method is literally called inline-image(), so that's what confused me. What would you call it? "embed"?Renata
R
5

As I couldn't find a established way to do this I had to solve it myself. I wrote a simple node module that wraps stylus.url() but replaces how SVGs are inlined.

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

Except for some checks it 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 + "')");
Renata answered 1/3, 2015 at 15:49 Comment(0)
C
5

Stylus now has this functionality built in:

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

The embedurl function with utf8 support was added in version 0.54.0 on March 5th 2016.

Commence answered 23/3, 2016 at 23:14 Comment(0)
C
0

Use CSS Literal:

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

Compiling to:

   .svg {
      background: url('data:image/svg+xml;base64,PD94bWwg[...]');
   }
Chromyl answered 14/2, 2017 at 18:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.