svg-sprite vs svg-sprite-loader vs gulp-svgmin vs gulp-svgstore vs gulp-svg-sprite vs gulp-iconfont
SVG Processing and Icon Management in Web Development
svg-spritesvg-sprite-loadergulp-svgmingulp-svgstoregulp-svg-spritegulp-iconfontSimilar Packages:
SVG Processing and Icon Management in Web Development

These npm packages are designed to streamline the process of handling SVG graphics and icons in web development. They provide various functionalities such as creating icon fonts from SVG files, generating SVG sprites for optimized loading, minimizing SVG files for better performance, and managing SVG assets efficiently. By using these tools, developers can enhance their workflow, reduce load times, and ensure that their applications are visually appealing and performant.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
svg-sprite166,6341,982213 kB612 years agoMIT
svg-sprite-loader162,3482,032-1494 years agoMIT
gulp-svgmin72,504340-74 years agoMIT
gulp-svgstore43,23064317 kB14 years agoMIT
gulp-svg-sprite31,19564713.4 kB73 years agoMIT
gulp-iconfont24,32485242.6 kB15a year agoMIT
Feature Comparison: svg-sprite vs svg-sprite-loader vs gulp-svgmin vs gulp-svgstore vs gulp-svg-sprite vs gulp-iconfont

Icon Font Generation

  • svg-sprite:

    svg-sprite focuses on generating SVG sprites with advanced features, allowing for customization and optimization of the output, but does not create icon fonts.

  • svg-sprite-loader:

    svg-sprite-loader integrates SVG sprites into modern JavaScript frameworks, allowing SVG files to be imported as components, but does not handle icon font generation.

  • gulp-svgmin:

    gulp-svgmin does not generate icon fonts or sprites but optimizes SVG files by minimizing their size, which can indirectly benefit icon font generation by reducing the size of the original SVG files.

  • gulp-svgstore:

    gulp-svgstore allows developers to create a single SVG sprite from multiple SVG files, which can be referenced in the HTML. This package is useful for managing SVG assets without generating a font.

  • gulp-svg-sprite:

    gulp-svg-sprite does not focus on icon font generation but rather on creating SVG sprite sheets. It combines multiple SVG files into a single sprite, which can be referenced in the HTML, reducing the number of HTTP requests.

  • gulp-iconfont:

    gulp-iconfont enables the conversion of SVG files into icon fonts, allowing developers to use scalable vector icons in their projects. This package supports various font formats and provides options for customizing the output, such as font naming and styles.

Performance Optimization

  • svg-sprite:

    svg-sprite provides performance benefits through sprite generation and optimization features, ensuring that the final output is efficient and lightweight for web use.

  • svg-sprite-loader:

    svg-sprite-loader improves performance by allowing SVG sprites to be used as components, which can be optimized and lazy-loaded in modern applications.

  • gulp-svgmin:

    gulp-svgmin is specifically designed for performance optimization, minimizing SVG files to reduce their size and improve loading speed, making it essential for performance-focused projects.

  • gulp-svgstore:

    gulp-svgstore enhances performance by consolidating SVG assets into a single file, which can be loaded once and reused throughout the application, reducing load times.

  • gulp-svg-sprite:

    gulp-svg-sprite optimizes performance by reducing the number of HTTP requests through sprite generation, which can significantly enhance load times for web applications.

  • gulp-iconfont:

    gulp-iconfont does not directly optimize performance but provides a scalable solution for using icons, which can improve rendering times when using font files instead of multiple image files.

Ease of Use

  • svg-sprite:

    svg-sprite offers a range of features but may have a steeper learning curve due to its advanced customization options, making it better suited for experienced developers.

  • svg-sprite-loader:

    svg-sprite-loader is designed for use with Webpack, making it easy to integrate SVG sprites into modern applications, but may require familiarity with Webpack configuration.

  • gulp-svgmin:

    gulp-svgmin is easy to integrate into existing Gulp workflows, allowing for quick optimization of SVG files with minimal configuration required.

  • gulp-svgstore:

    gulp-svgstore is relatively easy to use, providing a simple way to manage SVG assets and create a single sprite file, but may require some understanding of Gulp tasks.

  • gulp-svg-sprite:

    gulp-svg-sprite is user-friendly for creating SVG sprites, with clear documentation and examples, making it accessible for developers of all skill levels.

  • gulp-iconfont:

    gulp-iconfont is straightforward to use for developers familiar with Gulp, providing a simple API for creating icon fonts from SVG files, but may require additional setup for font management.

Integration with Build Tools

  • svg-sprite:

    svg-sprite can be used independently of Gulp, but it may require additional setup for integration with build tools, making it less straightforward for Gulp users.

  • svg-sprite-loader:

    svg-sprite-loader is specifically designed for Webpack, allowing for easy integration into modern JavaScript applications, but is not compatible with Gulp.

  • gulp-svgmin:

    gulp-svgmin integrates smoothly with Gulp, enabling developers to include SVG optimization in their build processes without much hassle.

  • gulp-svgstore:

    gulp-svgstore is tailored for Gulp, making it easy to incorporate into existing Gulp tasks for managing SVG assets efficiently.

  • gulp-svg-sprite:

    gulp-svg-sprite is also designed for Gulp, allowing for easy integration into Gulp workflows, which is beneficial for developers already using Gulp for task automation.

  • gulp-iconfont:

    gulp-iconfont is built specifically for Gulp, making it a natural choice for projects that already use Gulp as their build tool, ensuring seamless integration.

Customization Options

  • svg-sprite:

    svg-sprite provides extensive customization options for sprite generation, allowing developers to fine-tune the output to meet specific project needs, making it suitable for complex applications.

  • svg-sprite-loader:

    svg-sprite-loader allows for customization in how SVGs are imported and used as components, providing flexibility for developers working with modern frameworks.

  • gulp-svgmin:

    gulp-svgmin focuses on optimization rather than customization, providing limited options for altering SVG files beyond minimizing their size.

  • gulp-svgstore:

    gulp-svgstore allows for some customization in how SVGs are stored and referenced, but is primarily focused on asset management rather than extensive customization.

  • gulp-svg-sprite:

    gulp-svg-sprite offers some customization options for sprite generation, such as output format and naming conventions, but may not be as flexible as other packages for complex requirements.

  • gulp-iconfont:

    gulp-iconfont provides various customization options for font generation, including the ability to specify font names, styles, and formats, allowing for tailored icon font solutions.

How to Choose: svg-sprite vs svg-sprite-loader vs gulp-svgmin vs gulp-svgstore vs gulp-svg-sprite vs gulp-iconfont
  • svg-sprite:

    Choose svg-sprite when you require a more comprehensive solution for generating and managing SVG sprites. It provides advanced features for creating sprites, including the ability to customize the output format and optimize the SVGs, making it suitable for complex projects.

  • svg-sprite-loader:

    Select svg-sprite-loader if you are using Webpack and need to import SVG files as React components or Vue components. This loader allows you to easily integrate SVG sprites into your components, providing a seamless development experience with modern frameworks.

  • gulp-svgmin:

    Opt for gulp-svgmin when your focus is on optimizing SVG files for performance. This package minimizes SVG files by removing unnecessary metadata, comments, and whitespace, resulting in smaller file sizes without sacrificing quality, which is crucial for faster loading times.

  • gulp-svgstore:

    Use gulp-svgstore if you want to create an SVG sprite that can be referenced in your HTML. This package allows you to store SVGs in a single file and reference them using <use> tags, which is beneficial for maintaining clean HTML and efficient SVG management.

  • gulp-svg-sprite:

    Select gulp-svg-sprite if you need to combine multiple SVG files into a single sprite sheet. This package is ideal for reducing HTTP requests and improving load times by consolidating your SVG assets into one file, making it easier to manage and use in your application.

  • gulp-iconfont:

    Choose gulp-iconfont if your primary goal is to create icon fonts from SVG files. It allows you to convert multiple SVG icons into a single font file, which can be easily included in your web projects for scalable and customizable icons.

README for svg-sprite

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.

Legal

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.