【问题标题】:How can I wrap a precompiled hogan.js template into an AMD module?如何将预编译的 hogan.js 模板包装到 AMD 模块中?
【发布时间】:2013-12-04 10:58:31
【问题描述】:

我正在尝试将预编译的 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' 

我在编译模板时做错了吗?包装函数时我做错了吗?该函数是否需要存在于全局范围内?

【问题讨论】:

    标签: javascript node.js requirejs mustache hogan.js


    【解决方案1】:

    所以问题在于我误解了模板预编译与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!');
            });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多