Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

svg-sprite

svg-sprite645.7kMIT2.0.4TypeScript support: definitely-typed

SVG sprites & stacks galore — A low-level Node.js module that takes a bunch of SVG files, optimizes them and bakes them into SVG sprites of several types along with suitable stylesheet resources (e.g. CSS, Sass, LESS, Stylus, etc.)

icon, icons, svg, png, sprite, spritesheet, stack, generator, css, sass, less, stylus, stylesheet, inline, html, vector, rwd, retina, mustache, gulpfriendly

readme

svg-sprite

Build Status npm version Coverage Status npm downloads

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.

For an up-to-date list of browsers supporting SVG in general respectively SVG fragment identifiers in particular (required for <defs> and <symbol> sprites as well as SVG stacks) please refer to caniuse.com.

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

Getting started

Crafting a sprite with svg-sprite typically follows these steps:

  1. You create an instance of the SVGSpriter, passing a main configuration object to the constructor.
  2. You register a couple of SVG source files for processing.
  3. 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

const fs = require('fs');
const path = require('path');
const SVGSpriter = require('svg-sprite');

// Create spriter instance (see below for `config` examples)
const spriter = new SVGSpriter(config);

// Add SVG source files — the manual way ...
spriter.add('assets/svg-1.svg', null, fs.readFileSync('assets/svg-1.svg', 'utf-8'));
spriter.add('assets/svg-2.svg', null, fs.readFileSync('assets/svg-2.svg', 'utf-8'));
/* ... */

// Compile the sprite
spriter.compile((error, result) => {
    /* Write `result` files to disk (or do whatever with them ...) */
    for (const mode in result) {
        for (const resource in result[mode]) {
            fs.mkdirSync(path.dirname(result[mode][resource].path), { recursive: true });
            fs.writeFileSync(result[mode][resource].path, result[mode][resource].contents);
        }
    }
});

// Or compile the sprite async
const { result } = await spriter.compileAsync();
/* Write `result` files to disk (or do whatever with them ...) */
for (const mode in result) {
    for (const resource in result[mode]) {
        fs.mkdirSync(path.dirname(result[mode][resource].path), { recursive: true });
        fs.writeFileSync(result[mode][resource].path, result[mode][resource].contents);
    }
}

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>, // Main output directory
    log: <String|Logger>, // Logging verbosity or custom logger
    shape: <Object>, // SVG shape configuration
    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:

// Common svg-sprite config options and their default values
const config = {
    dest: '.', // Main output directory
    log: null, // Logging verbosity (default: no logging)
    shape: { // SVG shape related options
        id: { // SVG shape ID related options
            separator: '--', // Separator for directory name traversal
            generator: function () { /*...*/ }, // SVG shape ID generator callback
            pseudo: '~' // File name separator for shape states (e.g. ':hover')
        },
        dimension: {// Dimension related options
            maxWidth: 2000, // Max. shape width
            maxHeight: 2000, // Max. shape height
            precision: 2, // Floating point precision
            attributes: false, // Width and height attributes on embedded shapes
        },
        spacing: { // Spacing related options
            padding: 0, // Padding around all shapes
            box: 'content' // Padding strategy (similar to CSS `box-sizing`)
        },
        transform: ['svgo'], // List of transformations / optimizations
        meta: null, // Path to YAML file with meta / accessibility data
        align: null, // Path to YAML file with extended alignment data
        dest: null // Output directory for optimized intermediate SVG shapes
    },
    svg: { // General options for created SVG files
        xmlDeclaration: true, // Add XML declaration to SVG sprite
        doctypeDeclaration: true, // Add DOCTYPE declaration to SVG sprite
        namespaceIDs: true, // Add namespace token to all IDs in SVG shapes
        namespaceIDPrefix: '', // Add a prefix to the automatically generated namespaceIDs
        namespaceClassnames: true, // Add namespace token to all CSS class names in SVG shapes
        dimensionAttributes: true // Width and height attributes on the sprite
    },
    variables: {} // Custom Mustache templating variables and functions
}

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 has its 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:

const config = {
    mode: {
        css: true, // Create a «css» sprite
        view: true, // Create a «view» sprite
        defs: true, // Create a «defs» sprite
        symbol: true, // Create a «symbol» sprite
        stack: true // Create a «stack» sprite
    }
}

To further configure a sprite, pass in an object with configuration options:

// «symbol» sprite with CSS stylesheet resource
const config = {
    mode: {
        css: {
            // Configuration for the «css» sprite
            // ...
        }
    }
}

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.

// Common mode properties
const config = {
    mode: {
        <mode>: {
            dest: "<mode>", // Mode specific output directory
            prefix: "svg-%s", // Prefix for CSS selectors
            dimensions: "-dims", // Suffix for dimension CSS selectors
            sprite: "svg/sprite.<mode>.svg", // Sprite path and name
            bust: true || false, // Cache busting (mode dependent default value)
            render: { // Stylesheet rendering definitions
                /* -------------------------------------------
                css: false, // CSS stylesheet options
                scss: false, // Sass stylesheet options
                less: false, // LESS stylesheet options
                styl: false, // Stylus stylesheet options
                <custom>: ... // Custom stylesheet options
                -------------------------------------------    */
            },
            example: false // Create an HTML example document
        }
    }
}

Basic examples

A) Standalone sprite

Foreground image sprite with <symbol> elements (for being <use>d in your HTML source):

// «symbol» sprite with CSS stylesheet resource
const config = {
    mode: {
        symbol: {        // Create a «symbol» sprite
            inline: true // Prepare for inline embedding
        }
    }
}
B) CSS sprite with Sass resource

Traditional CSS sprite with a Sass stylesheet:

// «css» sprite with Sass stylesheet resource
const config = {
    mode: {
        css: { // Create a «css» sprite
            render: {
                scss: true // Render a Sass stylesheet
            }
        }
    }
}
C) Multiple sprites

<defs> sprite, <symbol> sprite and an SVG stack all at once:

// «defs», «symbol» and «stack» sprites in parallel
const config = {
    mode: {
        defs: true,
        symbol: true,
        stack: true
    }
}
D) No sprite at all

mode-less run, returning the optimized SVG shapes only:

// Just optimize source SVG files, create no sprite
const config = {
    shape: {
        dest: 'path/to/out/dir'
    }
}

Output destinations

Depending on your particular configuration, svg-sprite creates a lot of files that partly refer to each other. Several configuration options are controlling the exact location of each file, and you are well advised to spend a moment understanding how they interrelate with each other.

Relative destination paths refer to their ancestors as shown in the following scheme, with the current working directory being the ultimate base.

        Destination option                     Default               Comment
---------------------------------------------------------------------------------------------
cwd $   <dest>/                                .                     Main output directory
            <mode.css.dest>/                   css                   «css» base directory
                <mode.css.sprite>              svg/sprite.css.svg    Sprite location
                <mode.css.render.css.dest>     sprite.css            CSS stylesheet location
                <mode.css.render.scss.dest>    sprite.scss           Sass stylesheet location
                ...
            <mode.view>/                       view                  «view» base directory
                ...

By default, stylesheet resources are generated directly into the respective mode's base directory.

"Oh wait! Didn't you say that svg-sprite doesn't access the file system? So why do you need output directories at all?" — 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).

Pre-processor formats and the sprite location

Special care needs to be taken when you create a CSS sprite («css» or «view» mode) along with a stylesheet in one of the pre-processor formats (Sass, LESS, Stylus, etc.). In this case, calculating the correct relative SVG sprite path as used by the stylesheets can become tricky, as your (future) plain CSS compilation doesn't necessarily lie side by side with the pre-processor file. svg-sprite doesn't know anything about your pre-processor workflow, so it might have to estimate the location of the CSS file:

  1. If you truly configured CSS output in addition to the pre-processor format, svg-sprite uses your custom mode.<mode>.render.css.dest as the CSS stylesheet location.
  2. If you just enabled CSS output by setting mode.<mode>.render.css to true, the default value applies, which is mode.<mode>.dest / "sprite.css".
  3. The same holds true when you don't enable CSS output at all. svg-sprite then simply assumes that the CSS file will be created where the defaults would put it, which is again mode.<mode>.dest / "sprite.css".

So even if you don't enable plain CSS output explicitly, please make sure to set mode.<mode>.dest to where your final CSS file is intended to be.

Full configuration documentation

The complete configuration documentation including all options can be found here.

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 https://svg-sprite.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 GitHub releases for a complete release history.

Copyright © 2018 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.

changelog

Newer release notes are published on the GitHub release page: https://github.com/svg-sprite/svg-sprite/releases


1.6.0-alpha Maintenance pre-release (2020-01-18)

  • Remove support for Node < 8.0
  • Update dependencies (#306, #310)
  • Update documentation to use updated SVGO plugin name (#275)
  • Move mocha and should dependencies back to devDependencies again (#297, #285)
  • Add built-in templating function to encode hash signs (#294)
  • Fix verbose logging output (#279, #291)
  • Add option to prefix auto-generated namespace IDs (#292, #293)
  • Update preview templates to use SVG checker image (#287)

1.5.0 Maintenance release (2018-09-18)

  • Updated dependencies
  • Dropped support for Node.js < 6.4

1.4.1 Maintenance release (2018-09-18)

1.4.0 Maintenance release (2018-03-17)

  • Added more Node.js versions to Travis instructions
  • Updated dependencies
  • Updated SVGO version & test fixture (#258, #259)
  • Reformatted documentation code examples (#236)
  • Fix JSHint errors (#261)
  • Add support for simple shape ID generator (#240)
  • Add failing CPU detection workaround (#252)
  • Changed SVGO plugin defaults (#249)

1.3.7 Bugfix release (2017-06-01)

  • Updated dependencies
  • Fixed invalid markup in <defs> example html (#229)
  • Fallback for failing CPU detection (#217)
  • Fixed broken SVGO configuration in CLI (#216, #199)
  • Added glob base directory option to CLI (#220)
  • Fixed broken rootAttributes option in CLI (#228)

1.3.6 Bugfix release (2016-08-29)

  • Updated dependencies
  • Fixed LESS template mixin call (#187)
  • Fixed broken keyframe animation support (gulp-svg-sprite #63)

1.3.5 Bugfix release (2016-08-15)

  • Fixed file name regression bug (#186)

1.3.4 Bugfix release (2016-08-12)

  • Updated dependencies
  • Extended the ID generator callback signature (#176)
  • Improved usage pattern example (#177)
  • Added support for mode shorthand definitions in CLI mode (#183)

1.3.3 Bugfix release (2016-04-28)

  • Fixed CLI regression bug (#173)
  • Fixed CLI root attributes file handling (#144)

1.3.2 Feature release (2016-04-27)

  • Updated dependencies
  • Restored documentation image (#168)
  • Added CLI rendering options for defs/symbol/stack sprites (#160)
  • Added CLI option for external JSON config file (#160, #165)

1.3.1 Bugfix release (2016-04-17)

1.3.0 Major maintenance release (2016-04-14)

  • Updated dependencies
  • Tweaked .gitignore to ignore symlinked test files (closes #140) Reverted & made the files real copies
  • Updated documentation (grunt-svg-sprite #69)
  • Removed redundant require (#156)
  • Dropped support for Node.js < 4.0 and io.js
  • Added explicit sprite size in example document (#138)
  • Added XML entity resolution (#118)
  • Allow multiple selectors for ID / class namespacing (#109)
  • Switched to patched svg2png until media queries are properly supported (devDependencies)

1.2.19 Maintenance release (2016-01-11)

  • Updated dependencies
  • Temporarily fixed xmldom dependency problem (#135)

1.2.18 Maintenance release (2016-01-05)

  • Updated dependencies
  • Fixed inline embedding link in example templates (#130)
  • Fixed broken Less mixin support (#133)
  • Introduced support for custom shape orders (#131)

1.2.17 Maintenance release (2015-12-17)

  • Updated dependencies

1.2.16 Maintenance release (2015-12-01)

  • Updated dependencies
  • Improved log level config handling (#124)
  • Wrapped CSS url()s in quotes (#125)

1.2.15 Maintenance release (2015-11-24)

  • Updated dependencies

1.2.14 Bugfix release (2015-11-17)

  • Updated dependencies & test fixture
  • Added Node.js versions 4 & 5 to Travis tests
  • Fixed broken svg4everybody links (#122, gulp-svg-sprite #39)

1.2.13 Maintenance release (2015-11-06)

1.2.12 Maintenance release (2015-10-24)

  • Updated dependencies
  • Dropped example file extension restriction (#119)

1.2.11 Maintenance release (2015-10-07)

  • Updated dependencies

1.2.10 Maintenance release (2015-08-19)

  • Updated dependencies
  • Added browser compatibility hint (#106)
  • Added accessibility features to symbol sprites (#107)

1.2.9 Bugfix release (2015-08-19)

  • Updated dependencies
  • Fixed broken classname rendering function (#71)

1.2.8 Feature release (2015-08-12)

  • Updated dependencies
  • Introduced CSS positioning values floating point precision (#102)

1.2.7 Maintenance release (2015-07-29)

  • Updated dependencies
  • Fixed error in symbol example template (#99)

1.2.6 Feature release (2015-07-17)

  • Updated dependencies
  • Added CSS class namespacing (#42)

1.2.5 Maintenance release (2015-06-24)

  • Updated dependencies
  • Changed sprite file name handling (#97)

1.2.4 Bugfix release (2015-06-17)

  • Updated dependencies
  • Fixed invalid SVG validation regex (#94)

1.2.3 Bugfix release (2015-06-08)

  • Fixed string conversion regression (#89)
  • Updated dependencies

1.2.2 Feature release (2015-06-05)

1.2.1 Bugfix release (2015-06-04)

  • Fixed broken npm publish settings

1.2.0 Feature release (2015-06-04)

  • Updated dependencies & development dependencies (#67, #82)
  • Relocated the shape transformations list config option
  • Added custom root attributes support (#87)
  • Introduced a global post-processing transformation option (#64, #87)

1.1.2 Bugfix release (2015-04-22)

  • Fixed symbol example template regression bug (#70)
  • Added mixin option to CLI arguments
  • Fixed boolean CLI argument notation (#76)
  • Added whitespace replacement for shape IDs (#77)

1.1.1 Bugfix release (2015-04-19)

  • Updated dependencies & development dependencies
  • Added viewBox attribute to SVG stacks (#73)
  • Fixed example document path resolution bug (#70)
  • Allow negative viewBox values (#72)
  • Fixed symbol example document (#71)
  • Improved error log for invalid SVG files (#69)

1.1.0 Maintenance release (2015-04-04)

  • Updated dependencies & development dependencies
  • Added mixin option (#66; ATTENTION: May break custom templates!)
  • Node.js 0.12 compatibility

1.0.20 Bugfix release (2015-03-28)

  • Updated dependencies
  • Fixed several CLI bugs (#65)

1.0.19 Maintenance release (2015-03-08)

  • Changed alias for shape.dest CLI option
  • Updated dependencies
  • Fixed ID bug with view sprites
  • Fixed sprite CSS path calculation

1.0.18 Bugfix release (2015-02-20)

  • Removed excessive console output

1.0.17 Maintenance release (2015-02-20)

  • Optimized stylesheet templates
  • Introduced boolean hasCommon template variable
  • Updated dependencies
  • Fixed incomplete dimension CSS selector suffix (grunt-svg-sprite #31)

1.0.16 Bugfix release (2015-02-11)

  • Fixed broken previous release

1.0.15 Bugfix release (2015-02-11)

  • Fixed missing file extensions with CSS resources (#54)
  • Fixed broken sprite URL in css/view example HTML documents (#53)
  • Fixed wrong base path for intermediate SVG shapes
  • Removed the automatic dot prefix for CSS selectors (#55)

1.0.14 Maintenance release (2015-02-08)

  • Restructured documentation
  • Updated dependencies
  • Fixed error with falsy rendering configurations (#52)

1.0.13 Maintenance release (2015-01-28)

  • Fixed windows path separator bug (gulp-svg-sprite #6)
  • Made dimension attributes (width & height) optional (#45)
  • Added cache busting option for non-CSS sprites (#48)

1.0.12 Feature release (2015-01-27)

  • Added dimension CSS output for non-CSS sprites (#45)
  • Bumped lodash dependency version (#44)

1.0.11 Bugfix release

  • Fixed coordinate distortion in CSS sprites (#41)

1.0.10 Maintenance release

  • Added support for custom mode keys
  • Fixed external CLI transform configuration support
  • Fixed typos in README example (PR #39)
  • Added support for Windows file name globbing (#40)

1.0.9 Maintenance release

  • Updated dependencies
  • Introduced svg getter in templating shape variables
  • Fixed broken dimension argument in CLI version (#38)
  • Fixed logging error in SVGO optimization
  • Fixed missing XML namespaces in SVG stack
  • Fixed cache busting errors with example HTML document

1.0.8 Bugfix release

1.0.7 Feature release

  • Improved error handling
  • Improved XML & DOCTYPE declaration handling and fixed (grunt-svg-sprite #28)

1.0.6 Feature release

1.0.5 Bufix release

  • Fixed regression bug with SVG stacks
  • Added support for ID generator templates in CLI version (#37)

1.0.4 Bufix release

  • Fixed XML & doctype declaration bug with inline sprites (gulp-svg-sprite #2)
  • Added support for ID generator templates (#37)

1.0.3 Bufix release

  • Fixed dependency error (#36)

1.0.2 Maintenance release

  • Improved error handling

1.0.1 Maintenance release

  • Updated module dependencies

1.0.0 Next generation release

  • Rewritten from scratch (#23, #30)
  • Dropped libxmljs dependency for improving Windows support (e.g. grunt-svg-sprite #14)
  • Added support for view, symbol and stack modes (#27, #35, grunt-svg-sprite #24)
  • Strip off all file access methods, making the module a good basis for 3rd party tools (like Grunt & Gulp plugins) (#21, #25)
  • Improved command line version (#34)
  • Switched to relative positioning in CSS sprites (grunt-svg-sprite #23)
  • Made the configuration of Mustache templates and destinations more intuitive
  • Enabled customization of shape IDs
  • Enabled custom SVG transformations
  • Enhanced padding options (#24)
  • Added cache busting for css and view mode (enabled by default; #29)
  • Added support for meta data injection

For older release notes please see here.

About

The original svg-sprite was my first-ever Node.js module and featured CSS sprites only. The 1.0 release is rewritten from scratch and introduces a bunch of new features like less dependencies (for improved Mac OS and Windows compatibility), support for inline sprite formats and the removal of file-system access so that other libraries can build on top of it more easily. Derived libraries include:

iconizr, another project of mine, is based on svg-sprite and adds PNG fallbacks for the sprites so you can use them as universal icon systems for websites (Node.js module, Grunt plugin, PHP version and online service).