Easy way to precompile Emberjs Handlebar templates

2019-03-09 13:16发布

I'm enjoying emberjs a lot and would like to take the next step in a couple of my small, mobile apps and precompile my Ember/Handlebars templates as part of my build process.

I'd prefer to stay away from messing with Ruby and would like to use node.js as I'm more comfortable with using it.

I believe what I want to use is Ember.Handlebars.precompile, but unfortunately I'm unable to load the canonical ember.js file in a node environment. Example of a naive attempt from the node repl:

> var e = require('./ember');
ReferenceError: window is not defined
    at /Users/jeremyosborne/git/projects/ldls/client/lib/emberjs/src/ember.js:5:1
    at Object.<anonymous> (/Users/jeremyosborne/git/projects/ldls/client/lib/emberjs/src/ember.js:1596:2)
    --- stack trace, you get the idea ---

I think I've already figured out how to set them up in my code so that they work correctly with my views, I just want to compile them in an environment outside of a browser DOM.

In lieu of getting the canonical ember.js to load in node, are there a specific set of files that I can pluck from the ember repo and use to compile my templates?

EDIT I did a kluge fix that works great but gets an F for maintainability. I grabbed all the Handlebars code minus the reference to the window object. Then I followed with the Ember.Handlebars.Compiler code, replacing Ember.create with Object.create, exporting my Ember object, and viola things work seemingly great in node (as in it works and the functions produced are templates). But I don't consider this an answer to my own question due to the aforementioned maintainafail, so still open for answers.

EDIT 2 The above turns out to be a total fail. Perhaps there's something wrong in the procedure, but using Ember.Handlebars.precompile or Ember.Handlebars.compile doesn't work. The templates get made, but when I use the precompiled templates attached to Ember.TEMPLATES in my code, they do not work. I only seem to be able to get templates to work when they are explicitly passed in the modified script tags, as suggested on the emberjs.com site.

EDIT 3 I figured out what I was doing wrong. My answer is below.

8条回答
Evening l夕情丶
2楼-- · 2019-03-09 13:46

The following gist contains a nodejs build script that will precompile all .handlebars files in a given folder:

https://gist.github.com/1622236

查看更多
Viruses.
3楼-- · 2019-03-09 13:50

I've published a version of ember-precompiler with a similar interface to the handlebars command line utility. You can install it from NPM:

npm install -g ember-precompile

and then run it as:

ember-precompile template... [-f OUTPUT_FILE]

It does essentially what you describe (and what the gist versions do too): mock out the missing components needed to run Ember and Handlebars, compile the templates and add them to Ember.TEMPLATES.

查看更多
登录 后发表回答