
Use of eval is handy when we need to automatically reload a template. However, in production, this is slow and unsafe. Moreover, when using CSP, we have to use 'unsafe-eval' which brings shame to most of us. It appears use of eval() is not needed because the template has already been translated to Javascript. We just need to bind "jade" to its local scope. So, we add an additional wrapper function binding "jade" to the local scope. Moreover, when compiling the template, we add a flag to the function to know it has already been compiled. In this case, we execute it with "jade" in its scope. Otherwise, we keep using eval. Quickly tested in both situations. Seem to work. Fix #274.
63 lines
1.9 KiB
JavaScript
63 lines
1.9 KiB
JavaScript
define(function() {
|
|
"use strict";
|
|
|
|
var jade = null,
|
|
builds = {};
|
|
|
|
var fetchText = function() {
|
|
throw new Error("Environment not supported.");
|
|
};
|
|
|
|
if (typeof process !== "undefined") {
|
|
var fs = require.nodeRequire("fs");
|
|
jade = require.nodeRequire("jade");
|
|
fetchText = function(path, callback) {
|
|
callback(fs.readFileSync(path, "utf-8"));
|
|
};
|
|
} else if ((typeof window !== "undefined" && window.navigator && window.document) || typeof importScripts !== "undefined") {
|
|
fetchText = function (url, callback) {
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open('GET', url, true);
|
|
xhr.onreadystatechange = function() {
|
|
if (xhr.readyState === 4) {
|
|
callback(xhr.responseText);
|
|
}
|
|
};
|
|
xhr.send(null);
|
|
};
|
|
}
|
|
|
|
return {
|
|
|
|
fetchText: fetchText,
|
|
|
|
load: function(name, req, onload, config) {
|
|
var path = req.toUrl(name + ".jade");
|
|
fetchText(path, function(text) {
|
|
if (jade === null) {
|
|
req(["libjs-jade"], function(jade) {
|
|
onload(jade.compileClient(text));
|
|
onload(text);
|
|
});
|
|
} else {
|
|
builds[name] = jade.compileClient(text);
|
|
onload(builds[name]);
|
|
}
|
|
});
|
|
|
|
},
|
|
write: function(plugin, name, write) {
|
|
if (builds.hasOwnProperty(name)) {
|
|
write("define('" + plugin + "!" + name +"', function () {" +
|
|
" var wfn = function (jade) {" +
|
|
" var fn = " + builds[name] + ";" +
|
|
" return fn;" +
|
|
" };" +
|
|
"wfn.compiled = true;" +
|
|
"return wfn;" +
|
|
"});\n");
|
|
}
|
|
}
|
|
};
|
|
});
|