Combine svg files into one with <symbol>
elements.
Read more about this in CSS Tricks article.
If you need similar plugin for grunt, I encourage you to check grunt-svgstore.
- fileName — the name of result file, default: 'svgstore.svg'
- prefix — prefix for ids of the elements, default: ''
- inlineSvg — output only
<svg>
element without<?xml ?>
andDOCTYPE
to use inline, default: false - transformSvg(svg, cb) — callback to modify svg libxmljs element and call
cb(err)
when done
The following script will combine circle.svg and square.svg into single svg file with
<symbol>
elements. Additionally pass through gulp-svgmin to minimize svg payload size.
var svgstore = require('gulp-svgstore')
var gulp = require('gulp')
var svgmin = require('gulp-svgmin')
gulp.task('default', function () {
return gulp.src('test/src/*.svg')
.pipe(svgmin())
.pipe(svgstore({ fileName: 'icons.svg', prefix: 'icon-' }))
.pipe(gulp.dest('test/'))
})
To inline combined svg into html body I suggest using gulp-inject.
The following gulp task will inject svg into
<!-- inject:svg --><!-- endinject -->
placeholder of test/src/inline-svg.html.
var svgstore = require('gulp-svgstore')
var inject = require('gulp-inject')
var gulp = require('gulp')
gulp.task('default', function () {
var svgs = gulp.src('test/src/*.svg')
.pipe(svgstore({ prefix: 'icon-', inlineSvg: true }))
function fileContents (filePath, file) {
return file.contents.toString('utf8')
}
return gulp
.src('test/src/inline-svg.html')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('test/dest'))
})
There is a problem with <use xlink:href="external.svg#icon-name">
in Internet Explorer,
so you should either inline everything into body with a
simple script like this or
polyfil with svg4everybody.
To add style="display:none"
use the following transformSvg function:
function transformSvg (svg, cb) {
svg.attr({ style: 'display:none' })
cb(null)
}
To remove all fill attributes (so you can set fill from css) use the following transformSvg function:
function transformSvg (svg, cb) {
svg.find('[fill]').forEach(function (child) {
child.attr('fill').removeAttr('fill')
cb(null)
}
Remove only particular fills (e.g. fill="none"):
function transformSvg (svg, cb) {
svg.find('[fill="none"]').removeAttr('fill')
cb(null)
}