forked from jonkemp/gulp-useref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (86 loc) · 3.67 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
99
100
101
102
103
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var useref = require('node-useref');
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var stripBOM = require('strip-bom');
var restoreStream = through.obj();
module.exports = function () {
return through.obj(function (file, enc, cb) {
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-useref', 'Streaming not supported'));
return cb();
}
var output = useref(file.contents.toString());
var html = output[0];
try {
file.contents = new Buffer(html);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-useref', err));
}
this.push(file);
cb();
});
};
module.exports.assets = function (options) {
var opts = options || {};
return through.obj(function (file, enc, cb) {
var output = useref(file.contents.toString());
var assets = output[1];
['css', 'js'].forEach(function (type) {
var files = assets[type];
if (files) {
Object.keys(files).forEach(function (name) {
var buffer = [];
var filepaths = files[name].assets;
if (filepaths.length) {
var searchPaths;
if (files[name].searchPaths) {
searchPaths = path.join(file.cwd, files[name].searchPaths);
} else if (opts.searchPath) {
if (Array.isArray(opts.searchPath)) {
if (opts.searchPath.length > 1) {
searchPaths = '{' + opts.searchPath.join(',') + '}';
} else if (opts.searchPath.length === 1) {
searchPaths = opts.searchPath[0];
}
} else {
searchPaths = opts.searchPath;
}
searchPaths = path.join(file.cwd, searchPaths);
}
filepaths.forEach(function (filepath) {
var pattern = path.join((searchPaths || file.base), filepath);
var filenames = glob.sync(pattern);
if (!filenames.length) {
filenames.push(pattern);
}
try {
buffer.push(stripBOM(fs.readFileSync(filenames[0])));
} catch (err) {
if (err.code === 'ENOENT') {
this.emit('error', 'gulp-useref: no such file or directory \'' + pattern + '\'');
} else {
this.emit('error', new gutil.PluginError('gulp-useref', err));
}
}
}, this);
var joinedFile = new gutil.File({
cwd: file.cwd,
base: file.base,
path: path.join(file.base, name),
contents: new Buffer(buffer.join(gutil.linefeed))
});
this.push(joinedFile);
}
}, this);
}
}, this);
restoreStream.write(file, cb);
});
};
module.exports.restore = function () {
return restoreStream.pipe(through.obj(), { end: false });
};