forked from emaphp/handlebars-template-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
47 lines (38 loc) · 1.44 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
var Handlebars = require('handlebars');
var loaderUtils = require('loader-utils');
var path = require('path');
var fs = require('fs');
function resolveContent(content, root) {
var includeRegex = /<!--include\s+([\/\w\.]*?[\w]+\.[\w]+)-->/g;
var matches = includeRegex.exec(content);
while (matches != null) {
var file = loaderUtils.urlToRequest(matches[1]);
var basename = path.basename(file);
var dirname = path.join(root, path.dirname(file));
var rawContent = readFile(basename, dirname);
content = content.replace(matches[0], rawContent);
matches = includeRegex.exec(content);
}
return content;
}
function readFile(filepath, root) {
var self = readFile;
if (typeof(self.buffer) == "undefined") {
self.buffer = {};
}
if (filepath in self.buffer) {
return self.buffer[filepath];
}
var content = resolveContent(fs.readFileSync(path.join(root, filepath), 'utf8'), root);
self.buffer[filepath] = content;
return self.buffer[filepath];
}
module.exports = function(content) {
this.cacheable && this.cacheable();
var callback = this.async();
content = resolveContent(content, this.context);
var fn = Handlebars.precompile(content);
callback(null, "var Handlebars = require('handlebars');\n" +
"module.exports = (Handlebars[\"default\"] || Handlebars).template(" + fn + ");");
};
module.exports.Handlebars = Handlebars;