-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (71 loc) · 2.76 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
var path = require('path');
var util = require('util');
var gutil = require('gulp-util');
var through = require('through2');
var Promise = require('bluebird');
var guid = require('guid');
var PLUGIN_NAME = 'gulp-construct';
module.exports = function(options) {
return through.obj(function(file, enc, cb) {
var self = this;
options = options || {};
var showLog = options.showLog;
var type = options.type;
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
var includerReg = options.includerReg;
if (!util.isRegExp(includerReg)) {
gutil.log(gutil.colors.red('[ERROR] includerReg is required'));
this.push(file);
return cb();
}
var content = file.contents.toString();
var promises = [];
try {
content = content.replace(includerReg, function(str, includeSrc) {
var fs = Promise.promisifyAll(require('fs'));
var tempKey = guid.raw();
includeSrc = path.join(options.baseSrc || "", includeSrc);
var promise = fs.readFileAsync(includeSrc)
.then(function(data) {
return {
key: tempKey,
value: data.toString()
};
})
.catch(function(e) {
showLog && gutil.log(gutil.colors.red('[ERROR] read include file failed, ' + e));
});
promises.push(promise);
return tempKey;
});
} catch (err) {
showLog && gutil.log(gutil.colors.red('[ERROR] replace include failed, ' + e));
}
Promise.all(promises)
.then(function(map) {
map.forEach(function(obj) {
if(type == 'css'){
obj.value = '<style>' + obj.value + '</style>';
}else if(type == 'js'){
obj.value = '<script>' + obj.value + '</script>';
}
content = content.replace(obj.key, obj.value);
});
file.contents = new Buffer(content);
self.push(file);
cb();
})
.catch(function(e) {
gutil.log(gutil.colors.red('[ERROR] concat file failed, ' + e));
self.push(file);
cb();
});
});
};