Skip to content

Instantly share code, notes, and snippets.

@sirreal
Last active November 15, 2022 22:25
Show Gist options
  • Save sirreal/7a775314a40f00be237d to your computer and use it in GitHub Desktop.
Save sirreal/7a775314a40f00be237d to your computer and use it in GitHub Desktop.
node-sass inline svgs via `svg()` function

Make it easy to include SVG strings inline via node-sass.

Escapes SVG (via encodeURIComponent + node-sass custom function).

Wraps <svg/> with appropriate url(data...) which I can never remember.

Call:

node-sass --source-map=true --functions=./node-sass-functions.js in.scss out.css

Usage:

@import "functions.scss";
div {
  background-image: svg('<svg></svg>');
}

Be sure to @import "functions.scss";!

// use svg('<svg />') anywhere!
@function svg($svg) {
@return url('data:image/svg+xml,' + uri-encode(unquote($svg)));
}
var types = require('node-sass').types
module.exports = {
'uri-encode($val)': function uriEncode(val) {
return (new types.String(encodeURIComponent(val.getValue())))
},
}
@strarsis
Copy link

Using sass with eyeglass one can also inline a SVG file directly:
eyeglass-file-text for plain text + binary files (as base64 string)
eyeglass-inline-svg (uses eyeglass-file-text above + eyeglass-inline-urlescape)
for plain text in data uris, notably SVG files.

More about eyeglass: https://github.com/sass-eyeglass/eyeglass

With best regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment