/
preheat.js
88 lines (65 loc) · 1.96 KB
/
preheat.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
76
77
78
79
80
81
82
83
84
85
86
87
88
var fs = require('fs')
, handlebars = require('handlebars')
, hotplates = require('./hotplates')
, plates
, partials
, header
, footer
, preheated
, target
, batching
;
function preheat(opts, cb) {
preheated = cb || function () { };
plates = {};
partials = {};
header = opts.amd ?
'require([\'' + opts.handlebarsSrc + '\'], function(HandlebarsArg) {\n' +
// until handlebars is fully amd compliant we patch it
' var Handlebars = HandlebarsArg || Handlebars;' :
'(function() {\n';
header = header +
' var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n';
footer = opts.amd ? '});' : '})();';
target = opts.target;
hotplates.on('templateCompiled', function (file, name, plate) {
plates[name] = plate;
update();
});
hotplates.on('partialRegistered', function (file, name, partial) {
partials[name] = partial;
update();
});
hotplates.on('burned', function () {
plates = {};
partials = {};
});
hotplates.on('batchStarted', function () {
batching = true;
});
hotplates.on('batchEnded', function () {
batching = false;
update();
});
return hotplates;
}
function update () {
// When heating templates in batch, don't precompile them each time, but rather when the batch ended
if (batching) return;
var output = [];
output.push(header);
Object.keys(plates).forEach(function (name) {
output.push('templates[\'' + name + '\'] = template(' + handlebars.precompile(plates[name]) + ');\n');
});
Object.keys(partials).forEach(function (name) {
output.push('Handlebars.registerPartial(\'' + name + '\', ' +
'template(' + handlebars.precompile(partials[name]) + '));\n');
});
output.push(footer);
output = output.join('');
fs.writeFile(target, output, function (err) {
if (err) console.trace();
preheated(err, output);
});
}
module.exports = preheat;