Search code examples
javascriptnode.jsmustachehogan.jsisomorphism

Require in mustache template the same on node as on browser


This question uses Hogan as an example but applies to any template.

I am trying to make something isomorphic (work on both the client and server). On the client if I require in a mustache file:

var tpl = require('./something.ms');

Then browserify + a transform detects this is a mustache file by extension and tpl is an Object and one of the functions is .render.

I would like exactly the same result if I was to run the above line with NodeJS.

By default Node just expects this file to be a javascript file and so the result just looks like this and errors:

(function (exports, require, module, __filename, __dirname) { <h1>some html</h1> ...

Solution

  • I am surprised this wasn't easier to find out about!

    http://nodejs.org/api/globals.html#globals_require_extensions

    Unfortunately it is deprecated though "Unlikely to go away". I actually think it solves a problem I haven't otherwise seen a solution for in this kind of instance.

    var Hogan = require('hogan.js');
    require.extensions['.ms'] = function(mod, file){
        var tpl = fs.readFileSync(file, {encoding:'UTF-8'});
        mod.exports = Hogan.compile(tpl);
    }