forked from ingro/gulp-template-compile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
56 lines (41 loc) · 1.64 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
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var tpl = require('lodash.template');
var PluginError = gutil.PluginError;
var PLUGIN_NAME = 'gulp-template-compile';
module.exports = function (options) {
options = options || {};
function compiler (file) {
var name = typeof options.name === 'function' && options.name(file) || file.relative;
var objectName = options.objectName || 'templates';
var IIFE_start = options.IIFE !== false ? '(function() {\n' : '';
var IIFE_end = options.IIFE !== false ? '})();' : '';
var templateHeader = IIFE_start + 'var ' + objectName + ' = {};';
var NSwrapper = '\n\n' + objectName + '["'+ name.replace(/\\/g, '/') +'"] = ';
var template = tpl(file.contents.toString(), options.templateSettings).source;
return templateHeader + NSwrapper + template + IIFE_end;
}
var stream = through.obj(function (file, enc, callback) {
if (file.isNull()) {
this.push(file);
return callback();
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!'));
return callback();
}
var filePath = file.path;
try {
var compiled = compiler(file);
file.contents = new Buffer(compiled);
file.path = gutil.replaceExtension(file.path, '.js');
} catch (err) {
this.emit('error', new PluginError(PLUGIN_NAME, err, {fileName: filePath}));
return callback();
}
this.push(file);
callback();
});
return stream;
};