• Stars
    star
    332
  • Rank 126,496 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Create SVG sprites or compile to <symbols>

gulp-svg-sprites Build Status

Table of contents

Install

Install it locally to your project.

$ npm install --save-dev gulp-svg-sprites

Windows note: Using Version < 4.0.0, make sure you also have all prerequisites for node-gyp.

Usage

With no configuration, gulp-svg-sprites will create the following files:

  1. svg/sprite.svg - Sprite Sheet containing all of your SVGs
  2. sprite.html - A preview page with instructions & snippets
  3. css/sprite.css - A CSS file with the code needed to use the sprite
var svgSprite = require("gulp-svg-sprites");

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite())
        .pipe(gulp.dest("assets"));
});

Then, if you had a facebook.svg file, you'd be able to use the following markup in your webpage:

<i class="icon facebook"></i>

PNG fallback

You can easily support old browsers by piping the new SVG sprite through to another gulp task. There will be a no-svg class generated automatically in the CSS, so you'll just need to use something like Modernizr to set the no-svg class on the <body> tag of your website.

var svgSprite = require("gulp-svg-sprites");
var filter    = require('gulp-filter');
var svg2png   = require('gulp-svg2png');

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite())
        .pipe(gulp.dest("assets")) // Write the sprite-sheet + CSS + Preview
        .pipe(filter("**/*.svg"))  // Filter out everything except the SVG file
        .pipe(svg2png())           // Create a PNG
        .pipe(gulp.dest("assets"));
});

Symbols mode

Pass mode: "symbols" to output SVG data as this CSS Tricks article outlines. You'll get an SVG file and a preview file showing how to use it.

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({mode: "symbols"}))
        .pipe(gulp.dest("assets"));
});

Defs mode

Pass mode: "defs" to output SVG data as this CSS Tricks article outlines. You'll get an SVG file and a preview file showing how to use it.

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({mode: "defs"}))
        .pipe(gulp.dest("assets"));
});

Custom selectors

By default, the filename will be used as the selector in the CSS, but this is how you'd override it (the %f will be replaced with the filename):

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            selector: "icon-%f"
        }))
        .pipe(gulp.dest("assets"));
});

Custom IDs

With the symbols or defs mode, it's probably the ID you'll want to override. No problem.

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            svgId: "svg-%f"
        }))
        .pipe(gulp.dest("assets"));
});

Custom filenames

You can also change the generated filenames with ease. For example, if you want to create a scss partial instead, you could just do:

// Custom CSS filename
gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            cssFile: "scss/_sprite.scss"
        }))
        .pipe(gulp.dest("assets"));
});

// Custom SVG filename
gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            svg: {
                sprite: "svg.svg"
            }
        }))
        .pipe(gulp.dest("assets"));
});

// Custom preview filename + custom SVG filename
gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            svg: {
                sprite: "svg.svg"
            },
            preview: {
                sprite: "index.html"
            }
        }))
        .pipe(gulp.dest("assets"));
});

Base size

Set the font-size of the .icon class. Just pass a plain number, no units.

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            baseSize: 16
        }))
        .pipe(gulp.dest("assets"));
});

No previews

If you don't want 'em. Works in all modes.

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            preview: false
        }))
        .pipe(gulp.dest("assets"));
});

Using the built-in SCSS template

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite({
            templates: { scss: true }
        }))
        .pipe(gulp.dest("assets"));
});

Advanced: custom templates

Templates use Lodash Templates - check out their docs for usage instructions. Or take a look at the default CSS or the default SCSS for tips.

You can get your hands on JUST the SVG Data and provide your own templates. For example, if you want to provide your own template for the CSS output, you could do this:

var config = {
    templates: {
        css: require("fs").readFileSync("./path/to/your/template.css", "utf-8")
    }
};

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite(config))
        .pipe(gulp.dest("assets"));
});

You can override all the templates used in the same way.

Advanced: data transforms

If you want to do some custom stuff with your templates, you might need to transform the SVG data before it gets to your template. There are two functions you can provide to do this and they'll override the internal ones. Override transformData and you'll have direct access to the data returned from svg-sprite-data. This will skip the few transformations that this library applies - so use with caution. (If you want to modify the data as well after our internal modifications, use afterTransform instead.)

// Synchronous
var config = {
    transformData: function (data, config) {
        return data; // modify the data and return it
    },
    templates: {
        css: require("fs").readFileSync("./path/to/your/template.css", "utf-8")
    }
};

// Asynchronous
var config = {
    asyncTransforms: true,
    transformData: function (data, config, done) {
        done(data); // modify the data and pass it
    },
    templates: {
        css: require("fs").readFileSync("./path/to/your/template.css", "utf-8")
    }
};

gulp.task('sprites', function () {
    return gulp.src('assets/svg/*.svg')
        .pipe(svgSprite(config))
        .pipe(gulp.dest("assets"));
});

You can override all the templates used here in the same way. If you are doing any async work in these callbacks set asyncTransforms to true in the config.

Options

Name Type Default Description
mode String sprite

Define which mode to run in. Can be either "sprite", "defs" or "symbols"

common String icon

By default, the class icon will be used as the common class. You can also choose your own.

selector String %f

Easily add prefixes/suffixes to the generated CSS classnames. The %f will be replaced by the filename.

layout String vertical

Define the layout of the items in the sprite. Can be either "vertical", "horizontal" or "diagonal".

svgId String %f

In symbols or defs mode, you'll probably want to override the ID on each element. The filename will be used as a default, but can be overridden.

cssFile String css/sprite.css

Define the path & filename of the CSS file. Using this, you could easily create a SASS partial for example.

svgPath String ../%f

Define the path to the SVG file that be written to the CSS file. Note: this does NOT alter the actual write-path of the SVG file. See the svg option for that.

pngPath String ../%f

If you're creating a PNG fallback, define the path to it that be written to the CSS file

preview Object

Paths to preview files

preview.sprite String sprite.html
preview.defs String defs.html
preview.symbols String symbols.html
svg Object

Paths to SVG files

svg.sprite String svg/sprite.svg
svg.defs String svg/defs.svg
svg.symbols String svg/symbols.svg
padding Number 0

Add padding to sprite items

asyncTransforms Boolean false

Use async transforms

baseSize Number 10

Set the base font-size for the icon element

transformData Function transformData

Override the default data transforms

afterTransform Function afterTransform

Apply additional data transforms AFTER the defaults

License

Copyright (c) 2017 Shane Osbourne

Licensed under the MIT license.

More Repositories

1

jekyll-gulp-sass-browser-sync

A starter project including full setup for Jekyll, GulpJS, SASS & BrowserSync
CSS
728
star
2

json-ts

Automatically generate Typescript Definition files or Flow types from JSON input.
JavaScript
202
star
3

laravel-docker

repo for upcoming blog post
PHP
123
star
4

dev-ip

Find a suitable IP host to view local websites on
JavaScript
118
star
5

html-injector

BrowserSync html injector
JavaScript
78
star
6

grunt-cache-breaker

Simple cache-breaker - appends a timestamp to an asset url
JavaScript
74
star
7

next-no-js

TypeScript
53
star
8

cra-docker

Create React App + Docker - multi-stage build example
JavaScript
50
star
9

serde-zod

Rust
45
star
10

arewereadyformobileyet

Using Lighthouse to provide automated analysis of what frameworks give you 'out of the box'
HTML
41
star
11

nginx-cors-plus

A simple nginx proxy that you can put in front of any domain to enable CORS.
Shell
31
star
12

actor-js

Exploring the potential benefits of implementing APIs in the style of the Actor Model, even in single-threaded programming environments such as Javascript.
TypeScript
30
star
13

egghead-redux-obs

JavaScript
29
star
14

browser-sync-spa

Better Single Page App support for BrowserSync
JavaScript
29
star
15

laravel4-backbone-marionette

A starter project complete with a build step
JavaScript
27
star
16

bs-fullscreen-message

Fullscreen, in-browser error/success messages
JavaScript
19
star
17

foxy

Proxy with response moddin'
JavaScript
18
star
18

bem-validator

JavaScript
16
star
19

eazy-logger

easy cli logger
JavaScript
14
star
20

tfunk

Multi-colour console output from Chalk with added awesome.
JavaScript
13
star
21

js-blade

Javascript port of Laravel's Blade Templating language for Node
JavaScript
13
star
22

resp-modifier

middleware for modifying a html response
JavaScript
12
star
23

gulp-contribs

Give your open-source contributors some credit - automatically list them in your readme.md, or anywhere else.
JavaScript
10
star
24

egghead-preact-up-and-running

10
star
25

m2run

The zero-config way to contribute to Magento 2.
Rust
9
star
26

action-typed

Better type safety from less typing - making Redux work more like Elm
TypeScript
9
star
27

redux-obs-v1

JavaScript
9
star
28

bs-rewrite-rules

UI interface for adding/removing/editing Browsersync's rewrite rules
JavaScript
8
star
29

bs-snippet-injector

JavaScript
6
star
30

staunch

Redux-style state management for large-scale apps. Powered by ImmutableJS & RxJS. Async built-in.
JavaScript
6
star
31

easy-extender

plugin/hooks interface
JavaScript
5
star
32

entry-wrap-webpack-plugin

Wrap entry points with any code
JavaScript
5
star
33

egghead-gulp-browserify

JavaScript
5
star
34

bs-flask

Debugging repo for BrowserSync + Flask
Python
5
star
35

laravel-backbone-boilerplate

Boiler-plate app for rapidly creating a project using Laravel & Backbone.
PHP
5
star
36

wptuts-map-directions

This is the source code used in this tutorial - http://wp.tutsplus.com/tutorials/creative-coding/give-your-customers-driving-directions-with-the-google-maps-api/
JavaScript
5
star
37

cache-breaker

Cache Breaking tasks
JavaScript
4
star
38

from_file

A simple convenience to deserialize a rust Struct or Enum directly from a file path.
Rust
4
star
39

img-compare

Stand alone image comparisons for Node JS
JavaScript
4
star
40

redux-observable

JavaScript
3
star
41

module-federation-first-framework

TypeScript
3
star
42

svg-sprite-data

JavaScript
3
star
43

wordpress-dev-helper

Helper Class that allows you to minify and concatenate your JS when working with Wordpress.
PHP
3
star
44

blog

TypeScript
3
star
45

shakyshane-blog

Source code for shakyshane.com
CSS
3
star
46

swag2ts

TypeScript
3
star
47

learn-regex

An introduction to regular expressions in JavaScript
CSS
2
star
48

update-checker

Check the NPM registry for package updates
JavaScript
2
star
49

lit-ssr-vercel

Astro
2
star
50

heartbeat-monitor

Keep track of items via heartbeats
JavaScript
2
star
51

learn-regex-dev

The development repo for my learn-regex app
JavaScript
2
star
52

cl-strings

multi-colour string template for Node.js apps
JavaScript
2
star
53

opt-merger

Merge defaults opts with cli or api
JavaScript
2
star
54

amjs

Actor Model + Web Workers
TypeScript
2
star
55

create-epic-store

default setup for redux + redux-observable with added 'register'
TypeScript
2
star
56

portscanner-plus

Get multiple available ports with optional names
JavaScript
2
star
57

emitter-steward

Cycle & reset allowed emitters
JavaScript
2
star
58

docker-php-nginx

PHP
2
star
59

highlightjs-themes

CSS
2
star
60

wptuts-wordpress-faq

The files for this article http://wp.tutsplus.com/tutorials/creative-coding/create-an-faq-accordion-for-wordpress-with-jquery-ui/
PHP
2
star
61

async-nested-router

TypeScript
1
star
62

laravel-php-5-6

Dockerfile
1
star
63

vite-xstate-router

TypeScript
1
star
64

localstorage-html5

Test area for local storage
1
star
65

cb2

Rust
1
star
66

prom-seq

Just a sequence of promises
JavaScript
1
star
67

docker-wp

PHP
1
star
68

rx-react

JavaScript
1
star
69

rs-playground

Rust
1
star
70

norman.js

Low-level value mapping
JavaScript
1
star
71

actix-multi

Rust
1
star
72

magento2

HTML
1
star
73

closeup.js

A modern, minimalist image zoomer.
JavaScript
1
star
74

topics

A documentation system for developer workflows that you will keep up to date.
Rust
1
star
75

p-diff

Fork of http://pdiff.sourceforge.net/
C++
1
star
76

wdifu

What did I f*** up?
C++
1
star
77

scrape

playing with chromes remote debug protocol
JavaScript
1
star
78

vctest

Testing!
1
star
79

css-reg-test

JavaScript
1
star
80

imm-validate

a forgiving validator/formatter
JavaScript
1
star