svg-sprite
is a low-level Node.js module that takes a bunch of SVG files, optimizes them and bakes them into SVG sprites of several types:
- Traditional CSS sprites for use as background images,
- CSS sprites with pre-defined
<view>
elements, useful for foreground images as well, - inline sprites using the
<defs>
element, - inline sprites using the
<symbol>
element - and SVG stacks.
It comes with a set of Mustache templates for creating stylesheets in good ol' CSS or one of the major pre-processor formats (Sass, Less and Stylus). Tweaking the templates or even adding your own custom output format is really easy, just as switching on the generation of an HTML example document along with your sprite.
Grunt, Gulp & Co.
Being a low-level library with support for Node.js streams, svg-sprite doesn't take on the part of accessing the file system (i.e. reading the source SVGs from and writing the sprites and CSS files to disk). If you don't want to take care of this stuff yourself, you might rather have a look at the available wrappers for Grunt (grunt-svg-sprite) and Gulp (gulp-svg-sprite). svg-sprite is also the foundation of the iconizr project, which serves high-quality SVG based CSS icon kits with PNG fallbacks.
Table of contents
Installation
To install svg-sprite globally, run
npm install svg-sprite -g
on the command line.
Getting started
Crafting a sprite with svg-sprite typically follows these steps:
- You create an instance of the SVGSpriter, passing a main configuration object to the constructor.
- You register a couple of SVG source files for processing.
- You trigger the compilation process and receive the generated files (sprite, CSS, example documents etc.).
The procedure is the very same for all supported sprite types («modes»).
Usage pattern
var spriter = new SVGSpriter(config);
spriter.add('assets/svg-1.svg', null, fs.readFileSync('assets/svg-1.svg', {encoding: 'utf-8'}));
spriter.add('assets/svg-2.svg', null, fs.readFileSync('assets/svg-2.svg', {encoding: 'utf-8'}));
spriter.compile(function(error, result) {
});
As you can see, big parts of the above are dealing with disk I/O. In this regard you can make your life easier by using the Grunt or Gulp wrappers instead of the standard API.
Configuration basics
Of course you noticed the config
variable passed to the constructor in the above example. This is svg-sprite's main configuration — an Object
with the following properties:
{
dest : <String>,
log : <String|Logger>, // Logging verbosity or custom logger
shape : <Object>, // SVG shape configuration
transform : <Array>, // SVG transformations
svg : <Object>, // Common SVG options
variables : <Object>, // Custom templating variables
mode : <Object> // Output mode configurations
}
If you don't provide a configuration object altogether, svg-sprite uses built-in defaults for these properties, so in fact they are all optional. However, you will need to enable at least one output mode (mode
property) to get reasonable results (i.e. a sprite of some type).
General configuration options
Many configuration properties (all except mode
) apply to all sprites created by the same spriter instance. The default values are:
var config = {
dest : '.',
log : null,
shape : {
id : {
separator : '--',
generator : function() { },
pseudo : '~'
},
dimension : {
maxWidth : 2000,
maxHeight : 2000,
precision : 2,
attributes : false,
},
spacing : {
padding : 0,
box : 'content'
},
meta : null,
align : null,
dest : null
},
transform : ['svgo'],
svg : {
xmlDeclaration : true,
doctypeDeclaration : true,
namespaceIDs : true,
dimensionAttributes : true
},
variables : {}
}
Please refer to the configuration documentation for details.
Output modes
At the moment, svg-sprite supports five different output modes (i.e. sprite types), each of them having it's own characteristics and use cases. It's up to you to decide which sprite type is the best choice for your project. The mode
option controls which sprite types are created. You may enable more than one output mode at a time — svg-sprite will happily create several sprites in parallel.
To enable the creation of a specific sprite type with default values, simply set the appropriate mode
property to true
:
var config = {
mode :
css : true,
view : true,
defs : true,
symbol : true,
stack : true
}
}
To further configure a sprite, pass in an object with configuration options:
var config = {
mode :
css : {
}
}
}
Common mode properties
Many mode
properties are shared between the different sprite types, but there are also type specific options. Please refer to the configuration documentation for a complete list of settings.
var config = {
mode :
<mode> : {
dest : "<mode>",
prefix : "svg-%s",
dimensions : "-dims",
sprite : "svg/sprite.<mode>.svg"
bust : true|false,
render : {
},
example : false
}
}
}
Basic examples
A.) Standalone sprite
Foreground image sprite with <symbol>
elements (for being <use>
d in your HTML source):
var config = {
mode :
inline : true,
symbol : true
}
}
B.) CSS sprite with Sass resource
Traditional CSS sprite with a Sass stylesheet:
var config = {
mode :
css : {
render : {
scss : true
}
}
}
}
C.) Multiple sprites
<defs>
sprite, <symbol>
sprite and an SVG stack all at once:
var config = {
mode :
defs : true,
symbol : true,
stack : true
}
}
D.) No sprite at all
mode
-less run, returning the optimized SVG shapes only:
var config = {
shape :
dest : 'path/to/out/dir'
}
}
NOTE ABOUT THE dest
OPTION(S)
"Didn't you say that svg-sprite doesn't access the file system? So why do you need an output directory?" — Well, good point. svg-sprite uses vinyl file objects to pass along virtual resources and to specify where they are intended to be located. This is especially important for relative file paths (e.g. the path of an SVG sprite as used by a CSS stylesheet).
Online configurator & project kickstarter
To get you quickly off the ground, I made a simple online configurator that lets you create a custom svg-sprite configuration in seconds. You may download the results as plain JSON, Node.js project, Gruntfile or Gulpfile. Please visit the configurator at http://jkphl.github.io/svg-sprite.
Advanced techniques
Meta data injection
In order to improve accessibility, svg-sprite can read meta data from a YAML file and inject <title>
and <description>
elements into your SVGs. Please refer to the meta data injection guide for details.
Aligning and duplicating shapes
For CSS sprites using a "horizontal"
or "vertical"
layout it is sometimes desirable to align the shapes within the sprite. With the help of an external YAML file, svg-sprite can not only control the alignment for each individual shape but also create displaced copies of them without significantly increasing the sprite's file size.
Tweaking and adding output formats
svg-sprite uses Mustache templates for rendering the various CSS resources. This makes it very easy to tailor the generated CSS / Sass / LESS / Stylus resources to your needs or add completely new output formats. Please refer to the templating guide to learn about the details.
Command line usage
svg-sprite comes with a pretty feature complete command line version. A typical example could look like this:
$ svg-sprite --css --css-render-css --css-example --dest=out assets/*.svg
Please refer to the CLI guide for further details.
Known problems / To-do
- SVGO does not minify element IDs when there are
<style>
or <script>
elements contained in the file
Changelog
Please refer to the changelog for a complete release history.
Legal
Copyright © 2015 Joschi Kuphal joschi@kuphal.net / @jkphl. svg-sprite is licensed under the terms of the MIT license. The contained example SVG icons are part of the Tango Icon Library and belong to the Public Domain.