-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
75 lines (58 loc) · 2.15 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
'use strict';
var through = require('through2');
var tpl = require('lodash.template');
var PluginError = require('plugin-error');
var replaceExtension = require('replace-ext');
var PLUGIN_NAME = 'gulp-template-compile';
var getNamespaceDeclaration = function(ns) {
var output = [];
var curPath = 'window';
if (ns !== 'window') {
var nsParts = ns.split('.');
nsParts.forEach(function(curPart, index) {
if (curPart !== 'window') {
curPath += '[' + JSON.stringify(curPart) + ']';
output.push(curPath + ' = ' + curPath + ' || {};');
}
});
}
return {
namespace: curPath,
declaration: output.join('\n')
};
};
module.exports = function (options) {
options = options || {};
function compiler (file) {
var name = typeof options.name === 'function' && options.name(file) || file.relative;
var namespace = getNamespaceDeclaration(options.namespace || 'JST');
var IIFE_start = options.IIFE !== false ? '(function() {\n':'';
var IIFE_end = options.IIFE !== false ? '})();':'';
var templateHeader = IIFE_start + namespace.declaration;
var NSwrapper = '\n\n' + namespace.namespace + '["'+ 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 = replaceExtension(file.path, '.js');
} catch (err) {
this.emit('error', new PluginError(PLUGIN_NAME, err, {fileName: filePath}));
return callback();
}
this.push(file);
callback();
});
return stream;
};