-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (42 loc) · 1.51 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
'use strict';
var pt = require('path');
var through = require('through2');
var File = require('vinyl');
/**
* @param {Object} [options]
* @param {Function} [options.fileName]
* @param {Function} [options.globalVariable]
* @param {Function} [options.nameFunction]
*/
module.exports = function templateCache(options) {
options = options || {};
options.fileName = options.fileName || 'templates.js';
options.globalVariable = options.globalVariable || 'templateCache';
options.nameFunction = options.nameFunction || nameFunction_default;
var js = '(function() {\n';
js += ' window[ \'' + options.globalVariable.replace(/'/g, "\\'") + '\' ] = {};\n';
return through.obj(
function transform(file, e, done) {
if (file.isBuffer()) {
js += ' ' + convertHtml(file.contents.toString(), file.relative, options);
}
done(null);
},
function flush(done) {
js += '}());';
this.push(new File({
path: options.fileName,
contents: new Buffer(js)
}));
done(null);
}
);
}
function nameFunction_default(templatePath) {
return templatePath;
}
function convertHtml(view, path, options) {
var wrapped = "'" + view.replace(/'/g, "\\'").replace(/\n/g, '\\n') + "'";
return 'window[ \'' + options.globalVariable.replace(/'/g, "\\'") + '\' ][ \'' +
options.nameFunction(path).replace(/'/g, "\\'") + '\' ] = ' + wrapped + ';\n';
}