Created
October 27, 2012 22:05
-
-
Save garth/3966591 to your computer and use it in GitHub Desktop.
Pre-compile emberjs handlebars templates with browserify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path') | |
var vm = require('vm') | |
var handlebarsjs = fs.readFileSync(__dirname + '/vendor/handlebars.js', 'utf8') | |
var emberjs = fs.readFileSync(__dirname + '/vendor/ember/ember.js', 'utf8') | |
browserify.register('handlebars', function (body, file) { | |
//dummy jQuery | |
var jQuery = function () { return jQuery } | |
jQuery.ready = function () { return jQuery } | |
jQuery.inArray = function () { return jQuery } | |
jQuery.jquery = "1.8.2" | |
jQuery.event = { fixHooks: {} } | |
//dummy DOM element | |
var element = { | |
firstChild: function () { return element }, | |
innerHTML: function () { return element } | |
} | |
var sandbox = { | |
// DOM | |
document: { | |
createRange: false, | |
createElement: function () { return element } | |
}, | |
// Console | |
console: console, | |
// jQuery | |
jQuery: jQuery, | |
$: jQuery, | |
// handlebars template to compile | |
template: body, | |
// compiled handlebars template | |
templatejs: null | |
} | |
// window | |
sandbox.window = sandbox | |
// create a context for the vm using the sandbox data | |
var context = vm.createContext(sandbox) | |
// load Handlebars and Ember into the sandbox | |
vm.runInContext(handlebarsjs, context, 'ember.js') | |
vm.runInContext(emberjs, context, 'ember.js') | |
//compile the handlebars template inside the vm context | |
vm.runInContext('templatejs = Ember.Handlebars.precompile(template).toString()', context) | |
//name the template and return | |
var fileName = path.basename(file) | |
return 'Ember.TEMPLATES["' + | |
fileName.replace(/.handlebars/, '') + | |
'"] = Ember.Handlebars.template(' + context.templatejs + ');' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://github.com/substack/node-browserify/blob/master/doc/methods.markdown#bregisterext-fn for more details