Skip to content

Instantly share code, notes, and snippets.

@matthewblewitt
Created December 7, 2019 11:43
Show Gist options
  • Save matthewblewitt/eb205de734c31a5812dfc746a8aa2dc5 to your computer and use it in GitHub Desktop.
Save matthewblewitt/eb205de734c31a5812dfc746a8aa2dc5 to your computer and use it in GitHub Desktop.
SVG symbols generator
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var dom = require('cheerio')
var args = process.argv.slice(2)
var $ = dom.load(
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0" style="display:none;"></svg>',
{ xmlMode: true }
)
var dir
var fileName
var svgNode
var symbolNode
function parse (file) {
if (path.extname(file) === '.svg') {
fileName = file.slice(0, -4)
file = fs.readFileSync(path.join(dir, file), 'utf8')
svgNode = $(file)
symbolNode = $('<symbol></symbol>')
symbolNode.attr('viewBox', svgNode.attr('viewbox'))
symbolNode.attr('id', fileName)
symbolNode.append(svgNode.contents())
symbolNode
.children()
.each(function (i, kid) {
$(kid)
.removeAttr('fill')
.removeAttr('stroke')
.removeAttr('style')
})
$('svg').append(symbolNode)
}
}
if (args && args.length) {
dir = args[0]
fs.readdir(dir, function (err, files) {
if (err) {
process.stderr.write(err)
return
}
files.forEach(parse)
process.stdout.write(`const svg = '${$.html()}'; \nexport default svg;`)
})
} else {
process.stderr.write('Directory not found.')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment