-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
73 lines (63 loc) · 2.12 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
'use strict';
const path = require('path');
const gutil = require('gulp-util');
const through = require('through2');
const PLUGIN_NAME = 'gulp-html-include';
function _normalizePath(input) {
const len = input.length;
const end = input[len - 1];
return input + (end === '/' ? '' : '/');
}
module.exports = function (options) {
const config = {
dest: './',
path: '/',
xhtml: false
};
const merged = Object.assign(config, options);
const mergedWithNormalizedPath = Object.assign(merged, {
path: _normalizePath(merged.path),
});
mergedWithNormalizedPath.passThroughAttributes = mergedWithNormalizedPath.passThroughAttributes || {};
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
throw new gutil.PluginError({
plugin: PLUGIN_NAME,
message: 'Streaming not supported'
});
}
const fileName = path.basename(file.path);
const fileType = path.extname(fileName);
const htmlName = fileName + '.html';
let includeContents;
const normalizedPath = path.join(mergedWithNormalizedPath.path, fileName);
const passThroughAttributes = Object
.keys(mergedWithNormalizedPath.passThroughAttributes)
.map(attr => `${attr}="${options.passThroughAttributes[attr]}"`)
.join(' ');
if (fileType === '.js') {
includeContents = `<script src="${normalizedPath}" ${passThroughAttributes}></script>`;
} else if (fileType === '.css') {
if (mergedWithNormalizedPath.xhtml) {
includeContents = `<link href="${normalizedPath}" rel="stylesheet" ${passThroughAttributes}/>`;
} else {
includeContents = `<link href="${normalizedPath}" rel="stylesheet" ${passThroughAttributes}>`;
}
} else {
this.push(file);
return cb();
}
const htmlFile = new gutil.File({
base: mergedWithNormalizedPath.dest,
contents: Buffer.from(includeContents),
path: path.join(mergedWithNormalizedPath.dest, htmlName)
});
this.push(htmlFile);
gutil.log('Generating file', htmlFile.path);
return cb();
});
};