-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (60 loc) · 2.06 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
var loaderUtils = require('loader-utils');
var njs = require('njs-compiler');
var swig = require('swig');
function NjsSwigPlugin(options) {
if (!options) {
options = {};
}
if (!options.tagName) {
options.tagName = 'compileNjs';
}
var that = this;
this.compiler = njs.create({runtime: options.runtime});
var swigOptions = {cache: false, locals: options.locals};
if (options.template_dir) {
swigOptions.loader = swig.loaders.fs(options.template_dir);
}
this.swig = new swig.Swig(swigOptions);
this.swig.setExtension(options.tagName, function (val) {
return that.compiler.compile(val);
});
this.swig.setTag(
options.tagName,
function () {
return true;
}, function (compiler, args, content, parents, opts, blockName) {
var val = '(function () {\n' +
' var _output = "";\n' +
compiler(content, parents, opts, blockName) +
' return _output;\n' +
'})()';
var res = '_output += _ext.' + options.tagName + '(' + val + ');\n';
return res;
},
true,
true
);
this.loader = function (source) {
var njsRequest = loaderUtils.getRemainingRequest(this);
var jsRequest = loaderUtils.getCurrentRequest(this);
var query = loaderUtils.parseQuery(this.query);
try {
var result = that.swig.render(source, {filename: njsRequest});
}
catch (e) {
throw e;
}
this.callback(null, result);
};
}
NjsSwigPlugin.prototype.apply = function (compiler) {
var that = this;
compiler.plugin("compilation", function (compilation) {
compilation.plugin('normal-module-loader', function (loaderContext, module) {
if (/\.js$/.test(module.request) && module.request.split(['!']).length == 1) {
loaderContext.loaders.push({module: that.loader, request: module.request, path: module.request});
}
});
});
};
module.exports = NjsSwigPlugin;