grunt-svgtemplater
Version:
Include and combine SVG files into your HTML to reference them as SVG templates
71 lines (57 loc) • 2.45 kB
JavaScript
var path = require('path');
var fs = require('fs');
module.exports = function (grunt) {
grunt.registerMultiTask('svgtemplater', 'Include and combine SVG files into your HTML to reference them as SVG templates', function () {
var target = this.target;
var svgtemplater = grunt.svgtemplater || {summary: {}};
grunt.util.async.forEach(this.files, function (el, next) {
var out_pattern = /<(svg[\s\S]+?id=['"]svgtemplater['"][\s\S]*?)>[\s\S]*?(<\/svg>)/mi;
var comment = '<!-- This code is auto-generated by svgtemplater. -->\n'
try {
var stat = fs.lstatSync(el.dest);
if (stat && stat.isDirectory()) {
grunt.fail.fatal('Destination for target %s is not a file', target);
}
} catch (err) {
grunt.fail.fatal('Destination file for target %s is does not exist', target);
}
var out = grunt.file.read(el.dest);
var tags = out.match(out_pattern);
if(tags === null) {
grunt.fail.fatal('Destination file for target %s has no occurence of <svg id="svgtemplater"></svg>', target);
}
else {
var combined_svg = '';
var names = [];
el.src.forEach(function (file) {
var ext = path.extname(file);
if(ext === '.svg') {
var name = path.basename(file, ext).toLowerCase();
if(names.indexOf(name) < 0) {
names.push(name);
var content = grunt.file.read(file);
var svg = content.match(/<svg[\s\S]*?>([\s\S]*?)<\/svg>/im);
if(svg) {
combined_svg += '<g id="svg-' + name + '">' + svg[1].replace(/\s{2,}/gm, ' ').trim() + '</g>';
grunt.log.writeln('✔ '.green + file + (' included').grey);
}
else {
grunt.log.writeln('x '.red + file + (' is not a valid SVG file').grey);
}
}
else {
grunt.log.writeln('x '.red + file + (' skipped due to duplicate filename').grey);
}
}
});
var open_tag = '<' + tags[1].replace(/\s?style=['"][\s\S]*?['"]\s?/, '') + ' style="display: none;">\n';
var end_tag = '\n' + tags[2];
var out = out.replace(out_pattern, open_tag + comment + combined_svg + end_tag);
grunt.file.write(el.dest, out);
}
next();
}, this.async());
grunt.svgtemplater = svgtemplater;
});
};
;