Skip to content

Instantly share code, notes, and snippets.

@garth
Created October 27, 2012 22:05
Show Gist options
  • Save garth/3966591 to your computer and use it in GitHub Desktop.
Save garth/3966591 to your computer and use it in GitHub Desktop.
Pre-compile emberjs handlebars templates with browserify
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 + ');'
})
@garth
Copy link
Author

garth commented Oct 27, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment