如何将预编译的hogan.js模板封装到AMD模块中
How can I wrap a precompiled hogan.js template into an AMD module?
我正试图将预编译Mustache模板纳入我的构建过程中。我使用AMD进行代码组织,所以我想将编译后的函数封装到模块中。
我正在尝试以下操作:
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'
编译模板时我是否做错了什么?包装函数时我是否做错了什么?该功能是否需要在全球范围内运行?
所以这个问题是我误解了模板预编译与hogan
的工作方式:它输出的不是模板的普通JS"函数版本",而是一个预渲染字符串,您仍然需要将其传递给Hogan.template(str)
。
由于hogan的精简模板版本只有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!');
});
});
相关文章:
- 在AngularJS应用程序中使用封装指令和路由的推荐方式是什么
- Amd,希望确保某个东西总是最后执行
- 让Webpack管理Quirky AMD定义的最佳方式
- AngularJS中的封装窗口全局变量
- AMD格式是否要求模块为单件
- 闭包如何具体化数据封装
- 将javascript应用程序迁移到使用AMD的提示(例如requirejs)
- 使用解析为javascript源的.php,如何使用条件语句将javascript代码封装在php括号之间
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法加载Ace.js编辑器模式和主题(命名空间项目&AMD require.js&grunt
- Dojo AMD加载程序执行定义具有空/缺失依赖项的回调
- 如何将es6导入转换为AMD需要
- 电子构建器与电子封装器
- 将两个express应用程序封装在一个应用程序中
- 如何检索AMD的XHR响应代码(+时间戳)'大型Dojo
- AMD应用程序在浏览器中的加载速度是否快于CommonJS应用程序
- 使用Socket.io的异步模块加载(AMD)
- 使用AMD时未定义淘汰组件视图模型
- 试图封装$.getJSON和RequireJS
- 如何将预编译的hogan.js模板封装到AMD模块中