-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (58 loc) · 2.15 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* @format by moxhe
* @date 2017-09-26
*/
const fs = require('fs');
const path = require('path');
const EOL = '\n';
function compileTmpl(tmpl, filePath, self) {
var res = [];
tmpl.replace(/<\/script>/ig, '</s<%=""%>cript>');
res.push([
" function (it, opt) {",
" it = it || {};",
" with(it) {",
" var _$out_= [];",
" _$out_.push('" + tmpl
.replace(/\r\n|\n|\r/g, "\v")
.replace(/(?:^|%>).*?(?:<%|$)/g, function ($0) {
return $0.replace(/('|\\)/g, "\\$1").replace(/[\v\t]/g, "").replace(/\s+/g, " ")
})
.replace(/[\v]/g, EOL)
.replace(/<%\s*include\s+([^\s]+)\s*%>/g, function (all, filename) {
var data = '';
var fullname = path.resolve(filePath, filename);
self.addDependency(fullname);
if (fs.existsSync(fullname)) {
data = fs.readFileSync(fullname, { 'encoding': 'utf8' });
return "', " + compileTmpl(data, path.dirname(fullname), self) + "(it, opt), '";
} else {
throw new Error(`[imweb-tpl-loader]${fullname} not found.`);
}
})
.replace(/<%=\s*include\(['"]([^'"]+)['"]\)(\([^\)]*\))\s*%>/g, function (all, filename, args) {
var data = '';
var fullname = path.resolve(self.context, filename);
self.addDependency(fullname);
if (fs.existsSync(fullname)) {
data = fs.readFileSync(fullname, { 'encoding': 'utf8' });
return "', " + compileTmpl(data, path.dirname(fullname), self) + args + ", '";
} else {
throw new Error(`[imweb-tpl-loader]${fullname} not found.`);
}
})
.replace(/<%==(.*?)%>/g, "', opt.encodeHtml($1), '")
.replace(/<%=(.*?)%>/g, "', $1, '")
.replace(/<%-(.*?)%>/g, "', $1, '")
.replace(/<%(<-)?/g, "');" + EOL + " ")
.replace(/->(\w+)%>/g, EOL + " $1.push('")
.split("%>").join(EOL + " _$out_.push('") + "');",
" return _$out_.join('');",
" }",
"}"
].join(EOL).replace(/_\$out_\.push\(''\);/g, ''));
return res.join('');
}
module.exports = function (content) {
return 'module.exports = ' + compileTmpl(content, this.context, this);
};