forked from shanggqm/multi-mustache-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (77 loc) · 2.5 KB
/
index.js
File metadata and controls
92 lines (77 loc) · 2.5 KB
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
'use strict';
var loaderUtils = require('loader-utils');
var Hogan = require('hogan.js');
var minifier = require('html-minifier');
// https://github.com/kangax/html-minifier#options-quick-reference
var minifierDefaults = {
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
caseSensitive: true
};
var extend = function(target, source) {
target = JSON.parse(JSON.stringify(target));
Object.keys(source).forEach(function(key) {
target[key] = source[key];
});
return target;
};
module.exports = function(source) {
var query = loaderUtils.parseQuery(this.query);
var originalSource = source;
if (this.cacheable) {
this.cacheable();
}
// minify?
if (query.minify) {
// `?minify`
var minifierOptions = minifierDefaults;
// `?{minify:{...}}`
if (Object.prototype.toString.call(query.minify) === '[object Object]') {
minifierOptions = extend(minifierOptions, query.minify);
}
source = minifier.minify(source, minifierOptions);
}
var suffix;
if (query.noShortcut) {
suffix = 'return T; }()';
} else {
suffix = 'return T.render.apply(T, arguments); }';
}
var splitRegExp = /<script.+?id\s*?=\s*?"(.+?)".*?>([\s\S]+?)<\/script>/g;
var matched = [];
var match;
// if tpl file is multiple template or wrap with script tag?
if (source.match(splitRegExp)) {
while ((match = splitRegExp.exec(source)) !== null) {
if (match.length >= 3) {
matched.push({
id: match[1],
text: match[2]
});
} else {
// throw some info log
}
}
var multiExports = [];
matched.forEach(function(m) {
multiExports.push('"' + m.id + '": function(){ var T = new H.Template(' + Hogan.compile(m.text, {
asString: true
}) + ',' + JSON.stringify(m.text) + ',H);' + suffix);
});
multiExports.join(',');
return 'var H = require("hogan.js");\n' +
'module.exports = {' + multiExports.join(',') + '}';
}
return 'var H = require("hogan.js");\n' +
'module.exports = function() { ' +
'var T = new H.Template(' +
Hogan.compile(source, {
asString: true
}) +
', ' +
JSON.stringify(source) +
', H);' + suffix;
};