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

How can I wrap a precompiled hogan.js template into an AMD module?

本文关键字:封装 AMD 模块 js 编译 hogan      更新时间:2024-03-11

我正试图将预编译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!');
        });
});