Skip to content

Instantly share code, notes, and snippets.

@jibeetz
Last active March 19, 2024 12:30
Show Gist options
  • Save jibeetz/c2228a199da6ee9ee37f4f63a53e4bf7 to your computer and use it in GitHub Desktop.
Save jibeetz/c2228a199da6ee9ee37f4f63a53e4bf7 to your computer and use it in GitHub Desktop.
SVG Sprite Viewer
// npm install xml2json
// npm install node-fetch (not needed with node v17)
// The svg sprite is set at '/assets/icons/sprite.svg' location
// node sprite-viewer.js
// The script will generate an html file 'sprite.html'
var fs = require('fs');
var parser = require('xml2json');
var util = require('util');
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const fetch = require("node-fetch");
async function generateTemplate () {
// let sprite = await readFile('/assets/icons/sprite.svg', 'utf8');
let sprite = await fetch('/assets/icons/sprite.svg')
.then(async (response)=> {
return await response.text()
})
.catch(function(e) {
console.log("error", e);
});
let JSONsprite = JSON.parse(parser.toJson(sprite, {reversible: true}))
let template = sprite;
template += '<style>';
template += 'body{background-color: gray; display: flex; flex-wrap: wrap; font-family: arial; justify-content: center;} h3{margin: 0 0 15px; font-size: 0.8em;} div{background-color: #fff; margin: 30px; padding: 15px; text-align: center; width: 130px; display: flex; flex-direction: column; align-items: center; justify-content: space-between;} svg{width: 100px; height: 100px;}';
template += '</style>';
console.log(JSONsprite.svg.defs.symbol);
JSONsprite.svg.defs.symbol.forEach(symbol => {
template += '<div>'
template += '<h3>' + symbol.id + '</h3>'
template += '<svg>'
template += '<use xlink:href="#' + symbol.id + '"></use>'
template += '</svg>'
template += '</div>'
template += '\n'
})
await writeFile('sprite.html', template);
}
generateTemplate();
@JorgeSivil
Copy link

JorgeSivil commented Mar 13, 2020

Great, had some problems but because my SVG sprite was missing the <defs></defs>. Also for local file you must comment lines 17 to 23. Also line 2 is missing 'install' word

@jibeetz
Copy link
Author

jibeetz commented Mar 13, 2020

Thanks for the feedback and details on using a local file, I also updated line 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment