Created
July 5, 2017 23:24
-
-
Save KBizien/b5811ca5790999e28e7e72205f16cb04 to your computer and use it in GitHub Desktop.
builder svg
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
#!/usr/bin/env node | |
'use strict'; | |
/**************** | |
Modules & config | |
****************/ | |
var path = require('path'); | |
var fs = require('fs'); | |
var mkdirp = require('mkdirp'); | |
var cheerio = require("cheerio"); | |
var SVGSpriter = require('svg-sprite'); | |
var config = { | |
dest : './path/to/svg', | |
log : null, | |
shape : { | |
id : { | |
separator : '', | |
generator : function (name, file) { | |
var extName = path.extname(name); | |
var fileName = path.basename(name, extName); | |
return fileName; | |
} | |
}, | |
transform : ['svgo'], | |
}, | |
mode : { | |
symbol : true, | |
} | |
}; | |
var spriter = new SVGSpriter(config); | |
/**************** | |
Get svgs | |
****************/ | |
// Get svg folder content items and separate svgs files inside an array | |
var files = fs.readdirSync('./path/to/svg'); | |
var svgs = []; | |
files.forEach(function(file, index) { | |
var extName = path.extname(file); | |
if (extName == '.svg') { | |
svgs.push(file); | |
} | |
}); | |
// Loop through all svg files and add them to the spriter | |
svgs.forEach(function(file, index) { | |
var fromPath = path.join('./path/to/svg', file); | |
fs.stat(fromPath, function(err, stat) { | |
if (err) { | |
console.error("Error stating file.", error); | |
return; | |
} | |
if (stat.isFile()) { | |
spriter.add(path.resolve(fromPath), fromPath, fs.readFileSync(path.resolve(fromPath), {encoding: 'utf-8'})); | |
} | |
if ((svgs.length - 1) === index) { | |
compile(); | |
} | |
}); | |
}); | |
/**************** | |
Compile sprite | |
****************/ | |
function compile() { | |
spriter.compile(function(err, result, cssData) { | |
for (var mode in result) { | |
for (var type in result[mode]) { | |
mkdirp.sync(path.dirname(result[mode][type].path)); | |
fs.writeFileSync(result[mode][type].path, result[mode][type].contents); | |
} | |
} | |
}); | |
transform(); | |
} | |
/**************** | |
Custom transform sprite | |
****************/ | |
function transform() { | |
// Read and get symbols content | |
var spriteSymbol = fs.readFileSync('./path/to/sprite', 'utf8'); | |
// Load xml | |
var $ = cheerio.load(spriteSymbol, { | |
xmlMode: true, | |
}); | |
// Replace fill #888 by currentColor | |
$('svg').find('[fill="#888"]').each(function(){ | |
$(this).attr('fill', 'currentColor'); | |
}); | |
fs.writeFileSync('./path/to/dest/sprite.svg', $.xml(), 'utf8'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment