Add stylus function to import svg from a path and include it inline in css.
This js module add to stylus a function to read a svg file and import it inline in your css.
npm install stylus-svg
use('./node_modules/stylus-svg/index.js')
var stylus = require('stylus'),
stylusSvgImport = require('stylus-svg');
stylus(str)
.set('filename', 'nesting.css')
.use(stylusSvgImport())
.render(function(err, css){
// logic
});
var gulp = require('gulp'),
stylus = require('gulp-stylus'),
stylusSvgImport = require('stylus-svg');
// css
gulp.task('styles', function () {
return gulp.src('*.styl')
.pipe(stylus({
use: [
stylusSvgImport()
]
}))
.pipe(gulp.dest('css'));
});
You can add some bases directories to resolve path of your svg files.
stylusSvgImport({svgDirs: __dirname})
use('./node_modules/stylus-svg/index.js', {svgDirs: '/assets'})
It’s possible to add several paths:
stylusSvgImport({svgDirs: [__dirname, './other/path']})
But stylus syntax can be annoying:
svgDirs = '../node_modules' 'assets'
use('./node_modules/stylus-svg/index.js', {svgDirs: '/assets'})
.foo
background-image: svgImport('../svg/logo.svg')
You can also use the second argument to give some css to your svg (in stylus language)
.foo
background-image: svgImport('../svg/logo.svg', '
path
fill: rgba(255, 255, 255, .5)
')
This Stylus code do not access to outside stylus context (do not use variable defined outside).
By default, svg import remove width
and height
attributes to be sure that svg would not be considered as an non-vectorial background image by the browser:
It’s worth noting that the sizing algorithm only cares about the image's dimensions and proportions, or lack thereof. An SVG image with fixed dimensions will be treated just like a raster image of the same size.
Sources: MDN – Scaling of SVG backgrounds
You can set the third argument to false to not delete it.
.foo
background-image: svgImport('../svg/logo.svg', '', false)