2012-07-21 73 views
7

,所以我想EJS模板預編譯成.js文件你怎麼預編譯EJS模板文件

var compiled = ejs.compile(source); 
fs.writeFileSync(target, 'myTemplateFunction = ' + compiled); 

但serilalizes到

function (locals){ 
    return fn.call(this, locals, filters, utils.escape); 
} 

什麼是預編譯的最佳方式和將ejs模板寫入.js文件

回答

0

您可以創建一個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' }); 

由於modules are cached默認情況下,你應該能夠require('./template.js')只要您需要,它將擁有所有的連接預編譯模板。

+1

這與序列化模板無關,這是實際的問題。 – Avius 2017-01-04 16:23:04

0

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包ejs不提供這樣的屬性。