forked from mcfedr/gulp-unused-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (84 loc) · 2.86 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var through2 = require('through2'),
mime = require('mime'),
css = require('css'),
htmlparser2 = require('htmlparser2'),
gutil = require('gulp-util'),
path = require('path'),
_ = require('lodash');
var PLUGIN_NAME = 'gulp-unused-images';
function unusedImages(options) {
options = options || {log: true};
function addUsed(imageUrl) {
if (!imageUrl.match(/(data|http|https):/)) {
usedImageNames.push(path.basename(imageUrl));
}
}
var imageNames = [];
var usedImageNames = [];
var ngUsedImages = [];
var htmlParser = new htmlparser2.Parser({
onopentag: function onopentag(name, attribs) {
if (name === 'img') {
if (attribs.src) {
addUsed(attribs.src);
}
if (attribs['ng-src']) {
ngUsedImages.push(attribs['ng-src']);
}
}
// eg shortcut icon apple-touch-icon, it doesnt matter if we add extras that are not images
else if (name === 'link' && attribs.href) {
addUsed(attribs.href);
}
// eg msapplication-xxx
else if (name === 'meta' && attribs.content) {
addUsed(attribs.content);
}
// video posters
else if (name == 'video' && attribs.poster) {
addUsed(attribs.poster);
}
}
});
var transform = through2.obj(function (chunk, enc, callback) {
var self = this;
if (chunk.isNull()) {
self.push(chunk);
return callback();
}
if (chunk.isStream()) {
return callback(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
if (mime.lookup(chunk.path).match(/image\//)) {
imageNames.push(path.basename(chunk.path));
return callback();
}
try {
var ast = css.parse(String(chunk.contents));
ast.stylesheet.rules.forEach(function (rule) {
if (rule.type !== 'rule') {
return;
}
rule.declarations.forEach(function (declaration) {
var match = declaration.value.match(/url\(("|'|)(.+?)\1\)/);
if (match) {
addUsed(match[2]);
}
});
});
}
catch (e) {
htmlParser.write(String(chunk.contents));
}
self.push(chunk);
callback();
});
transform.on('finish', function () {
var unused = _.difference(imageNames, usedImageNames);
if (unused.length && options.log) {
this.emit('error', new Error('Unused images: ' + unused.join(', ') + '\nng-src: ' + ngUsedImages.join(', ')));
}
});
return transform;
}
module.exports = unusedImages;