Last active
October 26, 2019 13:33
-
-
Save NKjoep/c1175e4bb6f5bad836484e65261961ce to your computer and use it in GitHub Desktop.
svg spriter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "spriter", | |
"version": "0.0.0", | |
"main": "spriter.js", | |
"scripts": { | |
"start": "node spriter.js" | |
}, | |
"author": "Andrea D. <[email protected]>", | |
"license": "MIT", | |
"dependencies": { | |
"mkdirp": "^0.5.1", | |
"svg-sprite": "^1.5.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { readFileSync, writeFileSync, } = require('fs'); | |
const mkdirSync = require('mkdirp').sync; | |
const { dirname } = require('path'); | |
const SVGSpriter = require('svg-sprite'); | |
// your files | |
const files = [ | |
'./ours.svg', | |
// path/to/other/file-1 | |
// path/to/other/file-2 | |
// path/to/other/file-3 | |
// ... | |
]; | |
let counter = 0; | |
const spriterConfig = { | |
dest: './dist', | |
mode: { | |
symbol: { | |
bust: true, | |
inline: true, | |
examples: true | |
}, | |
}, | |
svg: { | |
xmlDeclaration: true, | |
namespaceIDs: true, | |
namespaceClassnames: true, | |
dimensionAttributes: true | |
}, | |
shape: { // SVG shape related options | |
id: { // SVG shape ID related options | |
separator: '--', // Separator for directory name traversal | |
generator: function (_, file) { | |
return `file-${++counter}-${file.path.toString().replace(/[^a-z0-9-]/ig, '-')}` | |
}, // SVG shape ID generator callback | |
pseudo: '~' // File name separator for shape states (e.g. ':hover') | |
}, | |
} | |
}; | |
// Create spriter instance (see below for `config` examples) | |
const spriter = new SVGSpriter(spriterConfig); | |
// Add SVG source files — the manual way... | |
files.forEach((filePath) => { | |
spriter.add(filePath, null, readFileSync(filePath, { encoding: 'utf-8' })); | |
}); | |
// Compile the sprite | |
spriter.compile((error, result) => { | |
if (error) { | |
console.error(error); | |
return; | |
} | |
/* Write `result` files to disk (or do whatever with them ...) */ | |
for (var mode in result) { | |
for (var resource in result[mode]) { | |
const path = result[mode][resource].path; | |
const dir = dirname(path); | |
const svg = result[mode][resource].contents.toString(); | |
mkdirSync(dir); | |
writeFileSync(path, svg); | |
} | |
} | |
console.log(`Done. Check the folder: ${spriterConfig.dest}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment