-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (67 loc) · 2.06 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
const PLUGIN_NAME = 'gulp-simple-inject';
// Dependencies
var through = require('through2'),
gutil = require('gulp-util'),
PluginError = gutil.PluginError,
replace = require('stream-replace'),
util = require('util'),
path = require('path');
var globals;
function inject(options) {
globals = {
cwd: process.cwd(),
htmlFiles: [],
cssRefs: "",
jsRefs: ""
};
if(util.isObject(options) && util.isString(options.cwd)) {
globals.cwd = path.resolve(globals.cwd, options.cwd);
}
return through.obj(transform, end);
}
function transform(file, enc, cb) {
var ext = path.extname(file.path),
relativePath = path.relative(globals.cwd, file.path);
if(file.isNull() || file.contents.length === 0) {
this.push(file);
} else if(ext === '.html') {
globals.htmlFiles.push(file);
} else if(ext === '.js') {
globals.jsRefs = `${globals.jsRefs}<script src="${relativePath}"></script>`;
this.push(file);
} else if(ext === '.css') {
globals.cssRefs = `${globals.cssRefs}<link rel="stylesheet" type="text/css" href="${relativePath}" />`;
this.push(file);
} else {
this.push(file);
}
cb();
}
function end(cb) {
var promises = [];
for(var htmlFile of globals.htmlFiles) {
promises.push(injectTags(htmlFile));
}
Promise.all(promises).then(htmlFiles => {
for(var htmlFile of htmlFiles) {
this.push(htmlFile);
}
cb();
}).catch(e => {
throw new PluginError(PLUGIN_NAME, `Failed to inject tags:\r\n${e}`);
});
}
function injectTags(htmlFile) {
return new Promise((resolve, reject) => {
htmlFile
.pipe(replace("<!-- inject:js -->", globals.jsRefs))
.pipe(replace("<!-- inject:css -->", globals.cssRefs))
.on('data', chunk => {
htmlFile.contents = chunk;
resolve(htmlFile);
}).on('error', e => {
reject(e);
});
});
}
module.exports = inject;