The process of compiling the template is in fact, converting the template from string, to javascript function, that we call later with our data. The compilation is the most expensive in terms of performance. So if you want performance, make sure you compile each template once and, cache the template functions and, reuse whenever you need.

So, now is where things get interesting. One of the most important features of Handlebars.js, is the support for pre-compiled templates. Pre-compiled templates, as the name states, are templates previously compiled instead being compiled in run time.

So this means, that we can get rid of the most expansive part of the template process!

Handlebars includes support for pre-compiling file-based templates. It is possible to have a script that finds all your templates (in separated files), compiles them and put them in one single file!

To achieve the compilation as a build step, we need to have installed node.js and npm.

After installing both, we need to install also the Handlebars npm package like this:

$ npm install handlebars -g

The -g flag installs the package globally, so it can be used in any project.

And now, we are ready to start using the precompiler. On the console you can do:

$ handlebars <input> -f <output>

The compiler will insert templates in Handlebars.templates. If, for example, you had an input file todos.handlebars, the compiler would insert it at Handlebars.templates.todos.
In my previous example and having a folder called “templates” with all my Handlebars.js templates, I would compile them like this:

$ handlebars templates/ -f templates.js

Handlebars then, would create a single file with the combined templates under templates folder in a templates.js file that we need to include in our page.