-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathejs-compile.js
50 lines (35 loc) · 1.32 KB
/
ejs-compile.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
/**
* EJS Compiler
*
* Compile all views/*.ejs files into a single /public/js/views.js file
*
* Simply require this module from the app.js to pre-compile all views when the server starts
*
* app.js:
*
* require("./ejs-compile");
*
*/
const fs = require('fs-extra');
const ejs = require('ejs');
const glob = require('glob-fs')({ gitignore: true });
function compile(view) {
let v = view.replace(/\//g,"_").replace(/\.ejs$/,"");
// console.log(v);
let template = new String(fs.readFileSync(view));
let f = ejs.compile(template, {client:true});
let f_str = f.toString();
f_str = f_str.replace("function anonymous(","ejs."+v+" = function(").replace("function(locals, escapeFn, include, rethrow", "function(locals, escapeFn, include = ejs.views_include(locals), rethrow")
return f_str;
}
let compiled = glob.readdirSync("views/**/*.ejs").map(compile).join("\n\n");
let output = `//EJS Compiled Views - This file was automatically generated on ${new Date()}
ejs.views_include = function(locals) {
console.log("views_include_setup",locals);
return function(path, d) {
console.log("ejs.views_include",path,d);
return ejs["views_"+path.replace(/\\\//g,"_")]({...d,...locals}, null, ejs.views_include(locals));
}
};
${compiled}`
fs.writeFile("public/js/views.js", output);