forked from drfisher/gulp-pug-template-concat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (44 loc) · 1.49 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
const gutil = require('gulp-util');
const PluginError = gutil.PluginError;
const through = require('through');
function pluginError (message) {
return new PluginError('gulp-pug-template-concat', message);
}
module.exports = function pugConcat(fileName, _opts) {
_opts = _opts || {};
if (!fileName) {
throw pluginError('Missing fileName');
}
var concatString = '';
var pugHelpers = '';
function write (file) {
if (file.isNull()) {
return;
}
if (file.isStream()) {
return this.emit('error', pluginError('Streaming not supported'));
}
// isolate filename from full path
var filename = file.path.replace(file.base, '').replace('.js', '').slice(1);
// split pug helpers and a template function and replace template name with filename
var splittedTemplate = file.contents.toString().split('function template');
pugHelpers = pugHelpers || splittedTemplate[0];
concatString += `${JSON.stringify(filename)}:function ${splittedTemplate[1]},\n`;
}
function end () {
// wrap concatenated string in template object
var templateString;
if(_opts.commonJS) {
templateString = 'module.exports'
} else {
templateString = `var ${_opts.templateVariable || 'templates'}`;
}
templateString += `=(function(){\n${pugHelpers}\n;return {\n${concatString}}})();`;
this.queue(new gutil.File({
path: fileName,
contents: new Buffer(templateString)
}));
this.queue(null);
}
return through(write, end);
}