如何将预编译的hogan.js模板封装到AMD模块中?

我试图将预编译我的胡须模板join到我的构build过程中。 我使用AMD代码组织,所以我想将我编译的function包装到模块中。

我正在尝试执行以下操作:

var fs = require('fs'); fs.readFile('template.html', 'utf-8', function(err, data){ function wrap(fnString){ var pre = 'define(function(){return '; var post = '});'; return pre + fnString + post; } var hogan = require('hogan.js'); var compiledFn = hogan.compile(data, {asString: true}); fs.writeFile('template.js', wrap(compiledFn), function(){console.log('written template module')}); }); 

当我尝试在应用程序中使用导出的函数时,我得到一个错误:

 Uncaught TypeError: Object [object global] has no method 'b' 

编译模板时我做错了什么? 包装function时我做错了什么? 该function是否需要在全球范围内生存?

所以这个问题是我误解了模板预编译与hogan工作方式:它不输出模板的vanilla JS“函数版本”,而是一个预渲染的string,你仍然需要传递给Hogan.template(str)

由于剥离的模板只有hkban版本只有2.5kb,我只是把它包括到我的AMD模块,并得到一切工作就好了:

 var fs = require('fs'); var Hogan = require('hogan.js'); var output = 'define(function(){\n'; output += 'var Templates = {};\n'; output += fs.readFileSync('template.min.js', 'utf-8') + '\n'; fs.readdir(process.cwd(), function(err, data){ if (err) console.log(err); data.forEach(function(el){ var s = el.split('.'); if (s[s.length - 1] === 'html'){ var precompiled = Hogan.compile(fs.readFileSync(process.cwd() + + el, 'utf-8'), {asString: true}); output += 'Templates[\'' + el.split('.')[0] + '\'] = new Hogan.Template(' + precompiled + ');\n'; console.log('Compiled template:', el); } }); output += 'return Templates;});'; fs.writeFile(process.cwd() + '/templates.js', output, function(){ console.log('Template build succeeded!'); }); });