UNPKG

2.02 kBJavaScriptView Raw
1/* jshint node:true */
2
3'use strict';
4
5var Transform = require('stream').Transform,
6 BufferStreams = require('bufferstreams'),
7 SVGOptim = require('svgo'),
8 gutil = require('gulp-util');
9
10var PLUGIN_NAME = 'gulp-svgmin';
11
12// File level transform function
13function minifySVGTransform(svgo) {
14 if (!(svgo instanceof SVGOptim)) {
15 svgo = new SVGOptim(svgo);
16 }
17
18 // Return a callback function handling the buffered content
19 return function(err, buf, cb) {
20 // Handle any error
21 if (err) {
22 return cb(new gutil.PluginError(PLUGIN_NAME, err));
23 }
24
25 // Use the buffered content
26 svgo.optimize(String(buf), function(result) {
27 if (result.error) {
28 return cb(new gutil.PluginError(PLUGIN_NAME, result.error));
29 }
30
31 // Bring it back to streams
32 cb(null, new Buffer(result.data));
33 });
34 };
35}
36
37// Plugin function
38function minifySVGGulp(options) {
39 var stream = new Transform({objectMode: true});
40 var svgo = new SVGOptim(options);
41
42 stream._transform = function(file, unused, done) {
43 // When null just pass through
44 if (file.isNull()) {
45 stream.push(file);
46 return done();
47 }
48
49 if (file.isStream()) {
50 file.contents = file.contents.pipe(
51 new BufferStreams(minifySVGTransform(svgo))
52 );
53 stream.push(file);
54 return done();
55 }
56
57 svgo.optimize(String(file.contents), function(result) {
58 if (result.error) {
59 return stream.emit('error', new gutil.PluginError(PLUGIN_NAME, result.error));
60 }
61 file.contents = new Buffer(result.data);
62 stream.push(file);
63 done();
64 });
65 };
66
67 return stream;
68}
69
70// Export the file level transform function for other plugins usage
71minifySVGGulp.fileTransform = minifySVGTransform;
72
73// Export the plugin main function
74module.exports = minifySVGGulp;
75