# Precompiling templates

Using the Handlebars precompiler, you can precompile your Handlebars templates to save time on the client and reduce the required runtime size of the handlebars library.

# Getting started

First, you will need to have Node.js and npm. Go to https://nodejs.org/en/download/ to find out how to do that on your OS.

Next, install the Handlebars npm package, which contains the precompiler.

npm install -g handlebars

Create a file name example.handlebars containing your template:

Handlebars <b>{{doesWhat}}</b> precompiled!

Run the precompiler.

handlebars example.handlebars -f example.precompiled.js

Include the Handlebars runtime and the precompile javascript.

<div id="output"></div>
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.runtime.js"></script>
<script src="example.precompiled.js"></script>
<script>
  var template = Handlebars.templates.example;
  document.getElementById('output').innerHTML = template({doesWhat: 'rocks!'})
</script>

The runtime is also available for download on the installation page.

# Optimizations

Because you are precompiling templates, you can also apply several optimization to the compiler. The first allows you to specify a list of the known helpers to the compiler

handlebars <input> -f <output> -k each -k if -k unless

The Handlebars compiler will optimize accesses to those helpers for performance. When all helpers are known at compile time, the --knownOnly option provides the smallest generated code that also provides the fastest execution.

# Usage

Precompile handlebar templates.
handlebars [template|directory]...

Options:
  -f, --output         Output File                                                                                      
  --map                Source Map File                                                    [string]  [default: undefined]
  -a, --amd            Exports amd style (require.js)                                                                   
  -c, --commonjs       Exports CommonJS style, path to Handlebars module                                 [default: null]
  -h, --handlebarPath  Path to handlebar.js (only valid for amd-style)                                     [default: ""]
  -k, --known          Known helpers                                                                                    
  -o, --knownOnly      Known helpers only                                                                               
  -m, --min            Minimize output                                                                                  
  -n, --namespace      Template namespace                                              [default: "Handlebars.templates"]
  -s, --simple         Output template function only.                                                                   
  -N, --name           Name of passed string templates. Optional if running in a simple mode. Required when operating
                       on multiple templates.                                                                           
  -i, --string         Generates a template from the passed CLI argument.
                       "-" is treated as a special value and causes stdin to be read for the template value.            
  -r, --root           Template root. Base value that will be stripped from template names.                             
  -p, --partial        Compiling a partial template                                                                     
  -d, --data           Include data when compiling                                                                      
  -e, --extension      Template extension.                                                       [default: "handlebars"]
  -b, --bom            Removes the BOM (Byte Order Mark) from the beginning of the templates.                           
  -v, --version        Prints the current compiler version                                                              
  --help               Outputs this message                                                                             

If using the precompiler's normal mode, the resulting templates will be stored to the Handlebars.templates object using the relative template name sans the extension. These templates may be executed in the same manner as templates. If using the simple mode the precompiler will generate a single javascript method. To execute this method it must be passed to the Handlebars.template method and the resulting object may be used as normal.

# Precompiling Templates Inside NodeJS

If you wish to precompile templates from inside NodeJS--without invoking "handlebars" from the command line--that can be done with Handlebars.precompile. Transmit the string result of this function to your clients, and they can in turn parse that with Handlebars.template.

let template = "Handlebars <b>{{doesWhat}}</b> precompiled!";
let Handlebars = require("handlebars");
let compiled = Handlebars.precompile(template);
console.log(compiled);

The output will be the following:

{"compiler":[8,">= 4.3.0"],"main":function(container,depth0,helpers,partials,data) {
    var helper, alias1=container.propertyIsEnumerable;

  return "Handlebars <b>"
    + container.escapeExpression(((helper = (helper = helpers.doesWhat || (depth0 != null ? depth0.doesWhat : depth0)) != null ? helper : container.hooks.helperMissing),(typeof helper === "function" ? helper.call(depth0 != null ? depth0 : (container.nullContext || {}),{"name":"doesWhat","hash":{},"data":data}) : helper)))
    + "</b> precompiled!";
},"useData":true}

On the client side you have Javascript along the lines of the following.

Handlebars.partials["test1"] = Handlebars.template({
  /** insert compiled output here **/
});

Finally, you can reference these templates dynamically in your Javascript.

var result = Handlebars.partials["test1"]({ name: "yourname" });
//do whatever you want with the result

# Integrations

Some npm-packages can be used to integrate the Handlebars precompiler into your build system (i.e. Webpack, Browserify...). Have a look at the integrations page:

Learn more: Integrations