Giter Site home page Giter Site logo

svg-sprite / svg-sprite Goto Github PK

View Code? Open in Web Editor NEW
1.9K 27.0 252.0 12.18 MB

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.)

Home Page: https://github.com/svg-sprite/svg-sprite

License: MIT License

JavaScript 88.58% CSS 0.32% HTML 10.29% Less 0.26% SCSS 0.28% Stylus 0.28%
svg sprite css mustache svgo html less sass

svg-sprite's Introduction

svg-sprite

npm version Build Status 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 of Object.values(result)) {
    for (const resource of Object.values(mode)) {
      fs.mkdirSync(path.dirname(resource.path), { recursive: true });
      fs.writeFileSync(resource.path, 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 of Object.values(result)) {
  for (const resource of Object.values(mode)) {
    fs.mkdirSync(path.dirname(resource.path), { recursive: true });
    fs.writeFileSync(resource.path, 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 [email protected] / @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.

svg-sprite's People

Contributors

arminrosu avatar bfred-it avatar dependabot-preview[bot] avatar dependabot[bot] avatar dmzkrsk avatar ert78gb avatar igloczek avatar jkphl avatar kazmiekr avatar korki43 avatar kreeg avatar kuppalli avatar louh avatar middric avatar midzer avatar mojoaxel avatar nikohoffren avatar peterblazejewicz avatar peterschultztarget avatar rdourado avatar sfe-efficy avatar sidnioulz avatar stefanjudis avatar stefanjudis-pa avatar stephenjwatkins avatar strager avatar thedancingcode avatar vincentbernat avatar xhmikosr avatar yisibl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

svg-sprite's Issues

ID cleanup bug

Sometimes when an SVG has ID's inside it (like when using a filter), the shortened ID after cleanup will be borked, i.e. it seems to have some extra characters or something like that. Example (output after cleanup and spriting):

<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40" viewBox="0 0 50 40" y="985" id="pencil">
<filter width="140%" height="140%" id="b�a" x="-20%" y="-20%">
  <feOffset dy="-1" in="SourceAlpha" result="offOut"/>
  <feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.7 0" in="offOut" result="matrixOut"/>
  <feBlend in2="matrixOut" in="SourceGraphic"/>
</filter>
<path filter="url(#b�a)" fill="#C7D1DA" d="M35.883 9.118c-1.938-1.939-5.08-1.939-7.02 0l7.02 7.018c1.937-1.938 1.937-5.08 0-7.018zm-17.918 10.899l-4.965 11.983 11.984-4.967 8.977-8.976-7.018-7.019-8.978 8.979zm-.599 8.672l-1.056-1.055 2.854-6.887s1.274.227 1.912.865c.639.639.465 1.846.199 2.111.266-.266 1.474-.439 2.111.199.639.639.865 1.914.865 1.914l-6.885 2.853z"/>
</svg>

Here you can see that filter has an ID 'ba' and the path should be using it -- but the path can't actually 'match it'. When I open this file in Chrome and inspect with developer tools, the ID is shown as "ba " (notice the space). Also, some others are shown as "b~a", "b|a" and such. The ones with 'invisible characters' do not match, and svg effects just disappear.

Hope this makes sense, and let me know if you need more info...

P.S. Also, many thanks for great module, much appreciated!

Mulitple src folders

Would it be possible to somehow set multiple src folders likes this:

src: [
'common/images/svg/',
'project1/images/svg/'
]

As it is right now, the script only handles the first src param and ignores the second one. I have multiple subprojects in which I would like to have both common svgs (used in multiple projects) and project specific svgs in different folders.

Needed update in css mode

It would be useful to render css file with prefix which can change dot to another symbol.
Example for scss
instead
.icon-1 {...}
.icon-2 {...}
.icon-3 {...}
do
%icon-1 {...}
%icon-2 {...}
%icon-3 {...}
in this case I can use @extend command for :after & :before pseudo-classes, or just another class or even a tag. And I dont need to paste sprite icon class to html file.
Such functionality would be very useful.

Media query support

Hey Joschi,

everything is running smooth and stable. ;)

There is only one thing missing, to make it perfect for my use case.
In my case I'm loading these icons only in case of a desktop window, so there is basically no need to set a background-image in case of smaller screensizes.

Do you see any chance or option to place a media query option ( or maybe a kind of wrapper option ) in svg-sprite?

Or another approach could be, that svg-sprite renders placeholders, so that I can do the rest by myself.

What do you think?

Thanks,
Stefan

Optional width / height / y / x

Hey guys,

I'm looking for a way to not add width and height to each svg element. Is there anyway to do that?

I was digging in the core, but looks like it is not optional. I will always get width and height on each of my elements.

I would love to have this as an option.

I'm getting each SVG in the sprite in this way:

<svg viewBox="0 0 32 32" width="32" height="32" id="share-icon" y="1210">

But I would love to get in like this:

<svg viewBox="0 0 32 32" id="share-icon">

In this way I could use the width and height from the parent.

Please let me know if there is anyway to do that, or please let me know if I could make a PR to add an optional config for it.

Thanks in advance.

Best regards,

Miguel

Change icon colors?

Is there a way to generate same SVG with multiple color overlays on a sprite? (or, a feature request)

Add possibillity to set background-alignment (left, right)

When inserting an icon it is not possible to align it to the right without breaking the sprites. This is a problem due to the current missing support of background-position-x and -y in Firefox. Having an option to set the horizontal background-position to an other value than "0" would be helfpul.

Add dimensions without dims suffix, custom selectors

Hi,

I've just started to use your Grunt plugin, and it's great!

I have a few issues with it that I couldn't wrap my head around:

  1. When I set dims to true, the rendered SASS adds a selector with a -dims suffix for each image. I would like the width/height to be added to the image selector itself, without the -dims suffix. That way I won't have to add another class to all the elements.
  2. I'm rendering SASS with the Grunt task. is there a way to add custom selector with a naming convention, like you did with the hover/active. Basically, I would like to add disabled to the SVG file name and for the Grunt plugin to add [disabled="disabled"] to the selector. For example:
    back-btn
    disabled.svg >> .back-btn[disabled="disabled"] in the SASS file.

Thanks!

Simple option to disable CSS/SCSS/LESS output (just generate sprites)

It would be great if between this and Iconizr there was a simple configuration option to disable CSS output. For example:

cssOutput: false

This would allow Iconizr/svg-sprite to generate the SVG & PNG image sprites but nothing more. Reason being that authors may be using background-size to size the images in different scenarios and in this case the background positions need entering by hand anyway so the generated style sheets are surplus to requirements.

Custom variable callback doesn't work correctly

I'm trying to use a similar variable definition as defined in the docs, but all it does is print the function as string into the template, which looks like this:

%svg-common {
    background-repeat: no-repeat;
    background-image: url(function (sprite, render) {
                    return render(sprite).split('.svg').join('.png');
                });

    .svg & {
        background-image: url(../image/sprite.svg);
    }
}

My configuration looks like this:

{
    variables: {
        png: function() {
            return function(sprite, render) {
                return render(sprite).split('.svg').join('.png');
            }
        }
    }
}

My template is this:

{{#common}}.{{/common}}{{^common}}%{{/common}}{{mixin}} {
    background-repeat: no-repeat;
    background-image: url({{{png}}});

    .svg & {
        background-image: url({{{sprite}}});
    }
}

Haven't found anything why mustache shouldn't run the function and instead print it. Any idea?

Defining a Modernizr style fallback image

I love this plugin. 👍

My question:

I would like to amend the scss render template so that I can provide a fallback to the png sprite via Modernizr. So, for example:

[class^="{{prefix}}"] {
    background-repeat: no-repeat;{{^common}}
    background-image: url('#{$img}ui/{{#sprite}}{{{sprite}}}{{/sprite}}{{^sprite}}{{#encode}}"{{{encoded}}}"{{/encode}}{{^encode}}{{{path}}}{{/encode}}{{/sprite}}');{{/common}}
    .no-svg & {
        background-image: url('#{$img}ui/{{#sprite}}{{{sprite}}}{{/sprite}}.png');
    }
}

However, I don't seem able to get the final output for the background-image correct. At present it is this:

background-image: url('#{$img}ui/sprite-name.svg.png');

What I would like output is this:

background-image: url('#{$img}ui/sprite-name.png');

Is there a way to omit the default file extension in the template so I can manually enter 'png' at the end (or specify the alternate encoding)?

Otherwise, thanks for an incredible plugin.

How set empty prefix?

Hello!

I generate full selectors in function and don't want use prefix. But I can't set empty prefix (it always equal '.') and I do this:

config: {
...
prefix: ''
...
}

generator: function(name) {
    var selector = doSmthng(name); // selector === '.selector .icon' 
    return selector.substr(1); // return 'selector .icon'
}

and then I have '.selector .icon' in css.

I do not like this crutch: selector.substr(1). How do I get rid of it?

No support for symlinks

In lib/svg-sprite.js:246:

if (stats.isFile() && (path.extname(file).toLowerCase() == '.svg')) {
  files.push(path.join(inputDir, file));
}

This won't catch any symbolic links out there, and one of my recent website designs relying on Iconizr has been hit by this. I don't particularly want to resort to copying the images as all systems I do web development on support symbolic links...

No optimization, just svg-sprite

Im struggling trying to make no optimization on the svg. My sources files are fine, but when compressed on a sprite, there is lot of "fails" on the outputted sprite. This have to do with SVO optimization, but Im not able to find out how or where.

Is there any way I can disable svg optimization and just use a compiled sprite from the original svg ?

Thanks a lot !

Can't render CSS in defs mode

Is it really impossible to render css/stylus/etc in defs mode? Need this for full control with CSS, e.g. adaptive sizing.
I did read all docs and I see this possible only in css/view modes.

Provide a way to not use spritedir

When I would like to place the SVG file directory into a specific folder (because I don't want the css anyway), I cannot just override the spritedir option.

Maybe using null as an value would be great to not put the file into any subdirectory.

Missing dependency mkdirp?

Updated to new version of svgo, and I am getting the following error:

Command

design_assets/node_modules/.bin/svg-sprite --cleanwith svgo --spritedir . --layout vertical -p 'icon' --common 'icons-sprite' -o 'design_assets/web/build/icons' --sprite icons-sprite --render '{"css":false,"html":{"dest":"icons_sprite.html"},"scss":{"template":"design_assets/web/templates/sprite.scss.mustache","dest":"_icons-sprite.scss"}}' 'design_assets/web/build/tmp'

Output:

module.js:340
    throw err;
          ^
Error: Cannot find module 'mkdirp'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/Users/orion/code/niche/design_assets/node_modules/svg-sprite/bin/svg-sprite.js:10:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

Add CSS class name namespacing

It would be desirable to not only have ID namespacing but also prefix CSS class names in SVGs with a custom string to avoid clashes. See #41.

Command line using the common option overrides the prefix option

We are using custom templates with the command line version the tool to build our spritesheet. When we run the follow command

svg-sprite --cleanwith svgo --spritedir . --layout vertical --common 'icons' -p 'icon' -o '/Users/orion/code/niche/design_assets/web/build/icons' --sprite icons-sprite --render '{"css":false,"html":{"dest":"icons_sprite.html"},"scss":{"template":"/Users/orion/code/niche/design_assets/web/templates/sprite.scss.mustache","dest":"_icons-sprite.scss"}}' '/Users/orion/code/niche/design_assets/web/build/tmp'

We see that the common option is overriding the prefix value.

Template:

// ***
// *** WARNING: This file is automatically generated by the
// *** <design_assets>/web/script/build_sprites.rb script,
// *** anything you change in this file will be overwritten.
// ***

$icon_size_15:  15;
$icon_size_20:  20;
$icon_size_25:  25;
$icon_size_30:  30;

$icon_size_natural: 100;

{{common}}
{{prefix}}

result:

// ***
// *** WARNING: This file is automatically generated by the
// *** <design_assets>/web/script/build_sprites.rb script,
// *** anything you change in this file will be overwritten.
// ***

$icon_size_15:  15;
$icon_size_20:  20;
$icon_size_25:  25;
$icon_size_30:  30;

$icon_size_natural: 100;

icons
icons

Is this intended behavior? We really need to get a second variable into the template and I would rather not have to write a custom node program to run it.

Add possibility to define custom css template

I'm missing this in the documentation, so I'm using the HTML example for rendering custom Scss files, which is, well, bad. Is there, or could there be a way to define a path to an example sprite.(less|sass|scss|css|styl).mustache and save that to a sprite.(less|sass|scss|css|styl)?

Use the viewBox attribute for determining the image dimensions

Currently, svg-sprite renders SVG images that have no width and height attributes via PhantomJS and gets the dimensions from the result. However, this should be ultima ratio. Instead, the viewBox attribute should be considered before rendering the image (in case it is present).

Offer FS-free API

First of all, a huge thanks!

I have been using your SVG tools for over a year now on many projects (through both the Grunt Plugin, & your web app) & they are flawless!

I have my own own project for creating SVG sprites for gulp - but it's full of rendering problems - to the point where I don't even use it my own projects (I use Iconizr as stated above.)

So, I wanted to 'borrow' all of the awesome SVG work you've been doing & wrap it in my streaming interface for gulp... but currently your lib does not allow this.

Basically, it's a shame to have FS access littered throughout your lib as it limits the use-cases dramatically.

Your lib is solving SVG related problems in a great way & it would be awesome to make the core consumable by other libs.

As a proof-of-concept, I forked & modded this: https://github.com/shakyShane/svg-sprite/blob/master/lib/svg-sprite.js

And you can see how you'd consume it here https://github.com/shakyShane/svg-sprite/blob/master/example-stream.js (this example being a stream).

It simply adds the addFile method which takes content as a string. This approach limits the code in the lib to doing what it does best - SVG manipulation. Implementing an interface like this would allow this project to be the core of other tools and basically be even more awesome!

I can see two options if you like the sound of this - moving the SVG stuff into a separate lib that does NO file access, or simply adding additional methods to this lib which can skip the FS stuff.

Personally, I think a separate lib would be amazing and would allow easier maintenance & iterations without the need for all the FS boilerplate. If it just works on strings & returns strings, it becomes infinitely more useful.

Thanks for listening, interested in your thoughts (I really don't want to publish a 'fork' as my own module). :)

Typo in svg-sprite.js:56 (installed from NPM: npm install svg-sprite -g)

Thank you for this tool! One minor issue, there's an extra close parentheses in line 56 of svg-sprite.js:

if ((typeof this.layout != 'undefined') && ()['vertical', 'horizontal', 'diagonal'].indexOf(this.layout) != -1)) {

should be:

if ((typeof this.layout != 'undefined') && (['vertical', 'horizontal', 'diagonal'].indexOf(this.layout) != -1)) {

Here's the error generated after installing on OSX:

/usr/local/lib/node_modules/svg-sprite/bin/svg-sprite.js:56
    if ((typeof this.layout != 'undefined') && ()['vertical', 'horizontal', 'diag
                                                ^
SyntaxError: Unexpected token )
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

Don't add escaped pseudoclass selectors unless required

I don't like how every sprite gets two selectors, even if I don't use pseudoclasses for my images.

.svg-spr1,
.svg-spr1\:regular {
        background-position: 0 0;
        background-repeat: no-repeat;
        background-image: url(svg/sprite.svg);
}

Could you consider adding an option to check if a pseudoclass selector is required before adding one?

How do you pass BOOLEAN TRUE on CLI

Hi!
Is this a bug, or is the documentation missing some crucial detail:
How do you pass BOOLEAN TRUE as --css-dimensions parameter to include dimension into scss -file when using the CLI?

Example command:
svg-sprite -c --css-dest /someCSSdir --css-sprite /someImageDir --cscss -p 0 --css-dimensions TRUE /images/*.svg

causes selector suffix to be "TRUE". I also tried integer 1, true, 'true' and "TRUE" and none of them works..

Thanks!

Empty SVG sprite

When there are no SVG source files inside the input directory, an empty SVG sprite is created. Instead, no sprite should be generated at all.

Inline SVG not working

Hi,

unfortunately the 'inline.svg' rendering option doesn't work for me.
I'm using svg-sprite with the grunt-iconizr task and the following settings:

iconizr       : {
  simple    : {
    src: ['icons/svg'],
    dest: 'icons/output',
    options     : {
      sprite    : 'svg-sprite'
      preview   : 'preview',
      keep      : true,
      dims      : false,
      level     : 0, // PNG optimization
      verbose   : 3,
      render: {
        'inline.svg': true,
        html: true
      }
    }
  }
},

It outputs everything but the inline sprite and the corresponding html preview.

svg-sprite - exceoption 'has no method 'size' '

Hey,

I'm running the following command, copied from your readme:

★ svg-sprite --keep --dims --css --out sprite --cleanwith svgo ./ingredients                               
Converting the SVG files in directory "./ingredients" to an SVG sprite ...
[TypeError: Object  has no method 'size']
An uncaughtException was found, svg-sprite will end.

Had the same bug by using it via grunt-svg-sprite.

Thanks. :)

XML processing instruction

Hi !

First, thanks for iconizr which I discovered recently as I have decided to use SVG sprites for the project I am working on. It makes things really easier and is really easily customizable.

However, I run into an issue, which apparently only occurs on windows: PhantomJS will hang forever if there is no XML processing instruction in the file. See ariya/phantomjs#12076 and domenic/svg2png#11.

To make it work by the time PhantomJS is fixed, I attempted to change the SVGO options through the cleanconfig option, disabling the removeXMLProcInst plugin.
That was ok for the pre-processed individual files, but not for the SVG sprite file itself, where the processing instruction was still missing.

I had a look at the code in svg-sprite, which actually generates the SVG sprite, and attempted to modify it so that it could add the missing line at the top when the removeXMLProcInst plugin was disabled by the user.

My attempt is available here: tkhyn@bdef274

I did not know anything about node.js 2 days ago and did not have the time to understand every aspect of how svg-sprite was working so there may be better ways to do the same thing, but this change makes things work for me. Through this report I mostly wanted to raise the issue and offer a possible solution. A similar approach may be used for the removeDoctype SVGO plugin (it does not look like any other plugin would require the same treatment).

Something worth noting but still about that: I modified the SVGObj.toSVG method so that the XML processing instruction is only removed when inline is true, and kept otherwise.

Thanks again,

Thomas

%% issue with sprite path

When we using %%, it means we want to @extend code from sprite.scss to our main.scss
And here is the problem
we can have such structure
-scss
---main.scss
---css
------sprite.scss
------svg
---------sprite.css-hdbch.svg
and in sprite.scss code we would have something like
%svg-common {
background-repeat: no-repeat;
background-image: url(svg/sprite.css-3feb3afe.svg);
}
%svg-ico-btn-slide-up {
background-position: 72.28260869565217% 0;
@extend %svg-common;
}
but when we exporting this code to main.scss
path to sprite wouldn't change
instead /css/svg/sprite.css-hdbch.svg sprite in /scss/css/svg/sprite.css-hdbch.svg folder
so it would be better to make sprite with its folders exactly in the root folder

Add option to customize symbol id based on file name

I just switched to gulp-svg-sprite from gulp-svg-sprites; it was pretty seamless for my use case, but one useful feature of the latter that doesn't appear to be supported in the former is config-based control over the value of the id attributes of the rendered <symbol>s.

gulp-svg-sprites actually doesn't appear to directly support this either, but there I was able to set the selector config option to something like icon-%f, and that would also affect the generated <symbol>'s id (not just the class names of the <svg> elements used in the HTML to include the sprite output), giving me output like:

<svg>
  <symbol id="icon-my-logo">
  <symbol id="icon-user-profile">
</svg>

when sourcing a directory of SVG files like:

icons/
  my-logo.svg
  user-profile.svg

This is handy because it keeps the file names concise and DRY (i.e., I don't need to name them icons/icon-my-logo.svg), while also "namespacing" the generated id attributes so that I don't have to worry about a naming collision unless I give another element on the page an id starting with icon- as well (which is unlikely anyway, and easier to remember not to do).

Would it be possible to add such a config option here? Or is there already a way to do this of which I'm unaware?

Offhand, I'd think maybe a good way to do it would be to provide an id configuration option with a similar string format:

id: 'icon-%f'

where %f is replaced by the id that's generated by the .svg source file name.

Hope that makes sense - please let me know if not.

Incidentally, great work here!

Malformed inline SVG <symbol> sprite

Hi!

I’m trying to generate an inline <symbol> sprite and can’t get valid SVG markup.

For some reason svg-sprite returns markup where all elements inside a <symbol> are nested one into another.

<!-- source -->
<svg>
  <symbol>
    <g>
      <path></path>
      <path></path>
    </g>
  </symbol>
</svg>

<!-- svg-sprite output -->
<svg>
  <symbol>
    <g>
      <path>
        <path></path>
      </path>
    </g>
  </symbol>
</svg>

I get this result on node v0.12.0 on either OS X 10.10 or Ubuntu 14.04.

I’ll share any details you might need to reproduce and solve the issue.

UPD: If I pass the same files to gulp-svg-sprite the problem goes away. <path> tags are self-closed and DOM tree is ok.

File extensions for CSS resources are not set properly

When specifying a CSS output resource path without file extension, the file extension should be added automatically:

/* ... */
scss    : {
    dest    : 'path/to/sass/without/extension'
},
/* ... */

should result in a file path/to/sass/without/extension.scss.

Support empty prefixes

Currently it is not possible to specify an empty prefix. The root causes is a check in svg-sprite.js which sets this._options.prefix to 'svg'if the prefix is set to any falsey value (which includes empty strings).

Errors in Windows 8.1 when using svg-sprite in a npm build script

In our development we have come upon the issue that when we create a npm build script as such:
"scripts": {
"build:svg": "svg-sprite --symbol --symbol-dest assets/tpl/dist --symbol-sprite sprite.svg assets/tpl/sources/svg/*.svg"
}
the windows terminal does not recognize that we wish to check all the svg files in a directory. This is because the *.svg is not read properly in windows.

Your script could be changed as to adapt to this situation. You could add the dependency mini-match for example.

unversioned dependency problem on locked dependencies project

Hello!

I might a problem using svg-sprite with grunt-svg-sprite when locking dependencies with npm shrinkwrap

on package.json, line 38 there's defined lodash as a dependency without version

"lodash": "lodash/lodash",

On grunt-svg-sprite dependencies, it generated with a git+https path, that would download any version, as far as I understand... possibly breaking the plugin if any major changes happen.

 "lodash": "git+https://github.com/lodash/lodash",

And, after locking dependencies with shrinkwrap it generates a relative path that's not working when I'm testing on different environments.

"from": "../../../../../../../var/folders/9f/39z7bx0s7sjgx9bqf1yqdjmh0000gn/T/npm-36893-3e27cd04/1421851729890-0.2797100490424782/ef3f0a0bb9f032d2eb3559fe9bcb5f49668c6f5f",

Does this all makes sense to you?
If so, I imagine the simplest solution would be to determine a version for lodash here, right?

Specify different paths for generated sprite and css

Hey again Joschi

Is it possible to have control over the path for where the css is stored, and another for the sprite ?
right now the sprites are stored inside the css folder. I would prefer to keep them outside. I can move the folder of course but then the paths in the css won't work...

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.