简体   繁体   中英

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

I'm trying to incorporate precompiling my Mustache templates into my build process. I'm using AMD for code organization so I'd like to wrap my compiled functions into modules.

I'm trying to do the following:

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')});

});

When I try to consume the exported function in my application I get an error though:

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

Am I doing something wrong when compiling the template? Am I doing something wrong when wrapping the function? Does the function need to live in global scope?

So the problem with this was that I misunderstood the way template precompilation works with hogan : It does not output a vanilla JS "function version" of your template but a pre-rendered string that you still need to pass to Hogan.template(str) .

Since the stripped down template only version of hogan is only 2.5kb I just included this into my AMD module and got everything working just fine like:

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!');
        });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM