This file is part of the documentation of svg-sprite — a free low-level Node.js module that takes a bunch of SVG files, optimizes them and creates SVG sprites of several types. The package is hosted on GitHub.
svg-sprite comes with four public methods:
- SVGSpriter([ config ]) — The spriter's constructor (always the entry point)
- SVGSpriter.add(file [, name, svg ]) — Registering source SVG files
- SVGSpriter.compile([ config ,] callback ) — Triggering the sprite compilation
- SVGSpriter.compileAsync([ config ,]) — Triggering the sprite compilation
- SVGSpriter.getShapes(dest , callback) — Accessing the intermediate SVG resources
To understand these methods' roles and interactions, please have a look at the following basic example first.
'use strict';
const fs = require('fs');
const path = require('path');
const SVGSpriter = require('svg-sprite'),
// 1. Create and configure a spriter instance
// ====================================================================
const spriter = new SVGSpriter({
dest: 'out', // Main output directory
mode: {
css: { // Create a CSS sprite
render: {
css: true // Render a CSS stylesheet
}
}
}
});
// 2. Add some SVG files to process
// ====================================================================
spriter.add(
path.resolve('assets/example-1.svg'),
'example-1.svg',
fs.readFileSync('assets/example-1.svg', 'utf-8')
);
/* ... */
spriter.add(
path.resolve('assets/example-x.svg'),
'example-x.svg',
fs.readFileSync('assets/example-x.svg', 'utf-8')
);
// 3. Trigger the (asynchronous) compilation process
// ====================================================================
spriter.compile((error, result, data) => {
// Run through all files that have been created for the `css` mode
for (const type of Object.values(result.css)) {
// Recursively create directories as needed
fs.mkdirSync(path.dirname(type.path), { recursive: true });
// Write the generated resource to disk
fs.writeFileSync(type.path, type.contents);
}
});
Constructor — This is the only method publicly exposed by svg-sprite, so it's always your entry point. Use it to create an instance of the spriter and access the remaining three methods.
- config
{Object}
(default:{}
) — Main configuration for the spriting process. As all configuration properties are optional, you may provide an empty object here or omit the argument altogether (no output files will be created then, but the added SVG files will be optimized nevertheless). Themode
configuration properties may also be specified when calling the.compile()
method (see below).
Registration of an SVG file — Before compilation, you'll need to register one or more SVG files for processing. As svg-sprite doesn't read the files from the disk itself, you'll have to pass both the path and the file contents explicitly. Alternatively, you may pass a vinyl file object as the first argument to .add()
, which comes in handy when piping resources from one process to another (as you would do with the Gulp wrapper anyway). Please see below for an example.
It is important to know that the spriter optimizes the SVG files as soon as you register them, not just when you compile your sprite. This way it is possible to call the .compile()
method several times, possibly passing in different render configurations without the need of repeating the optimization steps.
- file
{String|File}
— Absolute path to the SVG file or a vinyl file object carrying all the necessary values (the following arguments are ignored then). - name
{String}
(ignored with vinyl file) — The "local" part of the file path, possibly including subdirectories which will get traversed to CSS selectors using theshape.id.separator
configuration option. You will want to pay attention to this when recursively adding whole directories of SVG files (e.g. via glob). Whenname
is empty, svg-sprite will use the basename of thefile
argument. As an example, settingname
to"deeply/nested/asset.svg"
while giving"/path/to/my/deeply/nested/asset.svg"
forfile
will translate to the CSS selector"deeply--nested--asset"
. - svg
{String}
(ignored with vinyl file): SVG file content.
'use strict';
const fs = require('fs');
const path = require('path');
const SVGSpriter = require('svg-sprite');
const File = require('vinyl');
const glob = require('glob');
const spriter = new SVGSpriter({
dest: 'out',
mode: {
css: {
render: {
css: true
}
}
}
});
const cwd = path.resolve('assets');
// Find SVG files recursively via `glob`
glob.sync('**/*.svg', { cwd }, (err, files) => {
for (const file of files) {
// Create and add a vinyl file instance for each SVG
spriter.add(new File({
path: path.join(cwd, file), // Absolute path to the SVG file
base: cwd, // Base path (see `name` argument)
contents: fs.readFileSync(path.join(cwd, file)) // SVG file contents
}));
})
spriter.compile((error, result, data) => {
for (const type of Object.values(result.css)) {
fs.mkdirSync(path.dirname(type.path), { recursive: true });
fs.writeFileSync(type.path, type.contents);
}
});
});
Sprite compilation — Triggers an asynchronous sprite compilation process. You may pass in an optional output mode configuration object as the first argument in order to set the output parameters for that very run. You may call .compile()
multiple times, allowing for several different sprites being generated by the same spriter instance. For each run, the callback will be triggered independently, giving you access to the resources that were generated.
- config
{Object}
(optional) — Configuration object setting the output mode parameters for a single compilation run. If omitted, themode
property of the main configuration used for the constructor will be used. - callback
{Function}
— Callback triggered when the compilation has finished, getting three arguments:- error
{Error}
— Error message in case the compilation has failed - result
{Object}
— Directory of generated resources (see below) - data
{Object}
— Templating variables passed to Mustache for rendering the resources (see sprite & shape variables for details)
- error
Depending on the particular mode and render configuration, quite a lot of resources might be generated during a single compilation run. To understand the way svg-sprite returns these resources, please have a look at the following example:
spriter.compile(
{
css: {
render: {
scss: true
},
example: true
}
},
(error, result, data) => {
console.log(result);
}
);
The spriter is instructed to create a CSS sprite along with the accompanying stylesheet resource in Sass format and an example HTML document demonstrating the use of the sprite. The output will look something like this (shortened for brevity):
{
css: {
sprite: <File "css/svg/sprite.css.svg" <Buffer 3c 3f 78 ...>>,
scss: <File "css/sprite.scss" <Buffer 2e 73 76 ...>>,
example: <File "css/sprite.css.html" <Buffer 3c 21 44 ...>>
}
}
For each configured output mode (css
in the example), the result
object holds an item containing the resources generated for this particular mode. There is always a sprite
resource (obviously) and possibly an example
resource for the demo HTML document (if configured). For the css and view output modes, there are additional items named after the configured rendering configurations (scss
in the example).
Please note that the resources are always returned as vinyl files. Have a look above for an example of how to write these files to disk.
Sprite async compilation — Simple Promise wrapper on SVGSpriter.compile.
config {Object}
(optional) — Configuration object (same as in SVGSpriter.compile)
Promise
- Compilation Result
{Object}
Object containing fields:- result
{Object}
— Same as in SVGSpriter.compile - data
{Object}
— Same as in SVGSpriter.compile
- result
error {Error}
— Error message in case the compilation has failed
try {
const { result, data } = await spriter.compileAsync({
css: {
render: {
scss: true
},
example: true
}
});
console.log(result, data);
} catch (error) {
console.error(error);
}
Accessing the intermediate SVG resources — Sometimes you may want to access the single transformed/optimized SVG files that svg-sprite produces in an intermediate step. Depending on the configured shape transformations (e.g. SVG optimization with SVGO), svg-sprite will need some time for transforming the files, which is why accessing them must be an asynchronous task.
- dest
{String}
— Base directory for the SVG files in case they will be written to disk. - callback
{Function}
: Callback triggered when the shapes are available, getting called with two arguments:- error
{Error}
— Error message in case the shape access has failed. - result
{Array}
— Array of vinyl carrying the intermediate SVGs.
- error
const fs = require('fs');
const path = require('path');
spriter.getShapes(path.resolve('tmp/svg'), (error, result) => {
result.forEach(file => {
fs.mkdirSync(path.dirname(file.path), { recursive: true });
fs.writeFileSync(file.path, file.contents);
});
});