-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
73 lines (62 loc) · 1.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
var gutil = require('gulp-util');
var File = gutil.File;
var through = require('through2');
var SVGO = require('svgo');
/**
* File must be a buffer and not a string.
* @param {string} file Name of the output compressed JSON file.
* @param {Object} opts Other options.
*/
module.exports = function(file, opts) {
if (!file) {
throw new PluginError(
'gulp-svg-json-spritesheet',
'Missing parameter file for gulp-svg-json-spritesheet');
}
opts = opts || {
svgo: null
};
var spritesheet = {};
var svgCompressor = new SVGO(opts.svgo);
function compressEachFile(file, encoding, callback) {
if (file.isNull()) {
callback(null, file);
return;
}
if (file.isStream()) {
callback(new gutil.PluginError(
'gulp-svg-json-spritesheet', 'Streaming not supported'));
return;
}
try {
svgCompressor.optimize(file.contents.toString(), function(result) {
const filePath = file.path;
// Gets file name from file path.
if (opts.showFilePath) {
spritesheet[fileName] = result;
}
else {
const prefix = (opts.prefix) ? opts.prefix : '';
const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
spritesheet[prefix+fileName] = result;
}
});
} catch (error) {
this.emit('error', new gutil.PluginError('gulp-svg-json-spritesheet', error));
}
callback();
}
/**
* Once all files have been compressed, return compressed JSON file.
* @param {Function} callback
*/
function convertToJson(callback) {
var output = new File(file);
output.contents = new Buffer(JSON.stringify(spritesheet, null, '\t'));
output.path = file;
this.push(output);
callback();
}
return through.obj(compressEachFile, convertToJson);
};