-
Notifications
You must be signed in to change notification settings - Fork 12
/
handlebars-precompiler.js
250 lines (219 loc) · 8.21 KB
/
handlebars-precompiler.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Modified version of https://github.com/wycats/handlebars.js/blob/master/bin/handlebars
// Changed from command-line compiler to node module
var fs = require('fs'),
watch = require('watch'),
handlebars = exports.handlebars = require('handlebars'),
basename = require('path').basename,
uglify = require('uglify-js'),
_ = require('lodash');
/**
* Compiles all of the Handlebars templates
*
* @param {object} opts Options
* @param {boolean} opts.min Whether or not to minify the files
* @param {RegExp} opts.fileRegex File regular expression to match
* @param {string[]} opts.templates Template directories to compile
* @param {string} opts.output Output file name
* @param {boolean} opts.amd Exports amd style (require.js)
* @param {string} opts.handlebarPath Path to handlebar.js (only valid for amd-style)
* @param {boolean} opts.partial Compiling a partial template
* @param {string} opts.commonjs Exports CommonJS style, path to Handlebars module
*/
exports.do = function(opts) {
if (!opts.handlebarPath) {
opts.handlebarPath = '';
}
(function(opts) {
if (!opts.templates.length) {
throw 'Must define at least one template or directory.';
}
opts.templates.forEach(function(template) {
fs.statSync(template);
try {
fs.statSync(template);
} catch (err) {
throw 'Unable to open template file "' + template + '"';
}
});
}(opts));
// Convert the known list into a hash
var known = {};
if (opts.known && !Array.isArray(opts.known)) {
opts.known = [opts.known];
}
if (opts.known) {
for (var i = 0, len = opts.known.length; i < len; i++) {
known[opts.known[i]] = true;
}
}
var output = [];
if (opts.amd) {
output.push('define([\'' + opts.handlebarPath + 'handlebars\'], function(Handlebars) {\n');
} else if (opts.commonjs) {
output.push('var Handlebars = require("' + opts.commonjs + '");');
} else {
output.push('(function() {\n');
}
if (opts.partial) {
output.push(' var template = Handlebars.template, templates = Handlebars.partials = Handlebars.partials || {};\n');
} else {
output.push(' var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n');
}
function processTemplate(template, root) {
var path = template,
stat = fs.statSync(path);
// make the filename regex user-overridable
var fileRegex = /\.handlebars$/;
if (opts.fileRegex) {
fileRegex = opts.fileRegex;
}
if (stat.isDirectory()) {
fs.readdirSync(template).map(function(file) {
var path = template + '/' + file;
if (path.slice(-1) !== '~' && (fileRegex.test(path) || fs.statSync(path).isDirectory())) {
processTemplate(path, root || template);
}
});
} else {
var data = fs.readFileSync(path, 'utf8');
var options = {
knownHelpers: known,
knownHelpersOnly: opts.o
};
// Clean the template name
if (!root) {
template = basename(template);
} else if (template.indexOf(root) === 0) {
template = template.substring(root.length+1);
}
template = template.replace(fileRegex, '');
if(opts.amd && (opts.templates.length === 1 && !fs.statSync(opts.templates[0]).isDirectory())) {
output.push('return ');
}
output.push('templates[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
}
}
opts.templates.forEach(function(template) {
processTemplate(template, opts.root);
});
// Output the content
if (opts.amd) {
if(opts.templates.length > 1 || (opts.templates.length === 1 && fs.statSync(opts.templates[0]).isDirectory())) {
if(opts.partial){
output.push('return Handlebars.partials;\n');
} else {
output.push('return templates;\n');
}
}
output.push('});');
} else if (opts.commonjs) {
output.push('module.exports = templates;\n');
} else {
output.push('})();');
}
output = output.join('');
if (opts.min) {
output = uglify.minify(output, { fromString: true }).code;
}
if (opts.output) {
fs.writeFileSync(opts.output, output, 'utf8');
} else {
return output;
}
};
/**
* Compiles all of the Handlebars templates in the specified directory and monitors for changes.
*
* @deprecated This function is deprecated in favor of watch(), which allows for more options.
*
* @param {string} dir Directory with Handlebars templates
* @param {string} outfile Output file name
* @param {string[]} extensions An array of extensions (eg 'hbs') of files to compile as Handlebars templates
*/
exports.watchDir = function(dir, outfile, extensions) {
exports.watch(dir, outfile, {
extensions: extensions
});
};
/**
* Compiles all of the Handlebars templates in the specified directory and monitors for changes.
*
* @param {string} dir Directory with Handlebars templates
* @param {string} outfile Output file name
* @param {object} opts Options
* @param {string[]} opts.extensions An array of extensions (eg 'hbs') of files to compile as Handlebars templates (takes precedence over fileRegex)
* @param {number} opts.pollInterval Interval in milliseconds at which files are polled for changes (default: 500)
* @param {RegExp} opts.fileRegex A regular expression of the files to compile as Handlebars templates (instead of using .extensions)
* @param {boolean} opts.min Whether or not to minify the files (default: true)
* @param {boolean} opts.silent Silence console output (default: false)
* @param {boolean} opts.amd Exports amd style (require.js) (default: false)
* @param {string} opts.handlebarPath Path to handlebar.js (only valid for amd-style) (default: '')
* @param {boolean} opts.partial Compiling a partial template (default: false)
* @param {string} opts.commonjs Exports CommonJS style, path to Handlebars module (default: false)
*/
exports.watch = function(dir, outfile, opts) {
// defaults to send to .do()
var defaults = {
extensions: null,
pollInterval: 500,
fileRegex: /\.handlebars$/,
min: true,
silent: false,
amd: false,
handlebarPath: '',
partial: false,
commonjs: false
};
// merge arguments with defaults into options
var options = {};
_.merge(options, defaults, opts);
// process passed-in arguments
options.templates = [dir];
options.output = outfile;
if (options.extensions) {
options.fileRegex = new RegExp('\\.' + options.extensions.join('$|\\.') + '$');
}
/**
* Compiles all of the Handlebars templates if one of the files changes.
*
* @private
* @param {string} File name that changed, or an object of files that are being watched
* @param {object} Current stat object
* @param {object} Previous stat object (null if file is new)
*/
function compileOnChange(file, current, previous) {
var message;
if (typeof file === 'object' && previous === null && current === null) {
// Finished walking the tree and added listeners
message = 'watching ' + Object.keys(file).length + ' files';
} else {
var relativeFilename = file.replace(dir, '');
if (previous === null) {
message = 'new file detected: ' + relativeFilename;
} else if (current.nlink === 0) {
message = 'file removed: ' + relativeFilename;
} else {
message = 'file changed: ' + relativeFilename;
}
exports.do(options);
}
if (!options.silent) {
console.log('[handlebars-precompiler] ' + message);
}
}
// compile everything before we start watching
exports.do(options);
// find all matching files in the base directory and watch all of them for changes
watch.watchTree(dir, {
interval: options.pollInterval,
ignoreDotFiles: true,
persistent: true,
ignoreUnreadableDir: true,
filter: function(file) {
// This returns both files and directoroes
// Always allow directory to pass filter - apply regex to files only
var isDirectory = !/\/[^\/]*\.[^\/]+$/.test(file);
return isDirectory || options.fileRegex.test(file);
}
}, compileOnChange);
};