-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (52 loc) · 1.73 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
const chardet = require('chardet');
const fs = require('fs');
const loaderUtils = require('loader-utils');
const nunjucks = require('nunjucks');
const path = require('path');
module.exports = function(source) {
const options = loaderUtils.getOptions(this) || {};
const njkLoader = (startPath, alias) => {
const resolvePath = filePath => {
if (typeof alias === 'object') {
for (key in alias) {
const patt = new RegExp(`^~${key}`);
if (patt.test(filePath)) {
return path.join(alias[key], filePath.replace(patt, ''));
}
}
}
return path.resolve(startPath, filePath);
};
return {
getSource: filePath => {
const completePath = resolvePath(filePath);
this.addDependency(completePath);
const dataBuffer = fs.readFileSync(completePath);
// const charset = chardet.detect(dataBuffer);
return {
src: dataBuffer
.toString('UTF-8', 0, dataBuffer.length)
.replace(/({%.+?)>(.+?%})/gi, '$1>$2')
.replace(/({%.+?)<(.+?%})/gi, '$1<$2'), //将 > < 替换成实体字符,
path: completePath
};
}
};
};
if (options.tags) {
source = source
.replace(/({%.+?)>(.+?%})/gi, '$1>$2')
.replace(/({%.+?)<(.+?%})/gi, '$1<$2'); //将 > < 替换成实体字符
}
const env = new nunjucks.Environment(njkLoader(this.context, options.alias), {
tags: options.tags
});
if (options.globals) {
for (const key of Object.keys(options.globals)) {
env.addGlobal(key, options.globals[key])
}
}
const compiled = nunjucks.compile(source, env);
const rendered = compiled.render(options.context || {});
return rendered;
}