所以我想将 ejs 模板预编译成 .js 文件
var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);
但这会变成
function (locals){
return fn.call(this, locals, filters, utils.escape);
}
将 ejs 模板预编译和写入 .js 文件的最佳方法是什么
所以我想将 ejs 模板预编译成 .js 文件
var compiled = ejs.compile(source);
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled);
但这会变成
function (locals){
return fn.call(this, locals, filters, utils.escape);
}
将 ejs 模板预编译和写入 .js 文件的最佳方法是什么
您可以将 templates.js 文件(手动或在代码中)创建为空模块。然后在编译模板后,将编译后的函数附加到空模块上。
var ejs = require('ejs');
var fs = require('fs');
fs.writeFileSync('./template.js', 'module.exports = { }', 'utf8');
var compiled = ejs.compile(fs.readFileSync('./example.ejs', 'utf8'));
// Add an example function to the template file that uses the compiled function
require('./template').example = compiled;
// Get the example template again (this could be in another file for example)
var output = require('./template').example;
var html = output({ id: 10, title: 'Output' });
由于默认情况下会缓存模块,因此您应该可以在require('./template.js')
任何需要的地方进行缓存,并且它会附加所有预编译的模板。
Lodash _.template()方法在编译期间创建 EJS 模板函数的字符串表示形式,并将其作为源属性附加到编译后的函数。您可以将该字符串存储到 JS 文件中,将其嵌入到 HTML 中,或者在睡觉前将其读给您的孙子孙女。
例如:
> var _ = require('lodash');
> var compiled = _.template('Hi <%= user %>!');
> compiled({ user: 'Axel' })
"Hi Axel!"
> compiled.source
"function(obj) {
obj || (obj = {});
var __t, __p = '';
with (obj) {
__p += 'Hi' + ((__t = ( user )) == null ? '' : __t) + '!';
}
return __p
}"
> var fs = require('fs')
> var src = 'module.exports = ' + compiled.source;
> fs.writeFileSync('mylittlescript.js', src);
Webpack 的ejs-loader模块使用这种方法。另请注意,npm package ejs不提供此类源属性。