Handlebars precompilation and runtime: Efficient production use

Learn how Handlebars precompilation and the runtime reduce browser overhead and improve template rendering performance.

🎯 Introduction

In this article, you will learn about Handlebars precompilation. Sending template strings to the browser and compiling them there adds overhead. Precompilation moves that work ahead of time so the browser only loads a lightweight runtime, making rendering faster and better suited to production.


🧱 The runtime versus the full build

Handlebars offers two ways to work with templates:

BuildFeaturesUse cases
Full build (handlebars)Compiles and renders templatesNode.js backends and development
Runtime (handlebars/runtime)Renders compiled templates; smaller sizeBrowsers and production

The full build can compile template strings into functions at runtime. The runtime-only build can only execute templates that have already been compiled.


✨ Why precompile templates?

Using the full Handlebars build in a browser involves these steps:

  1. Load the full JavaScript build, which is larger.
  2. Pass a template string to Handlebars.compile().
  3. Obtain a rendering function and pass in data to produce HTML.

All of this happens in the browser, increasing loading and execution time.

Precompilation changes the process:

  1. Use Node.js to compile templates into JavaScript during the build step.
  2. Load only the much smaller runtime in the browser.
  3. Call the compiled functions directly to render templates.
Think of precompilation as preparing ingredients ahead of time: when it is time to serve, the browser only needs to heat the meal, improving speed and the user experience.

💡 Precompiling from the command line

Handlebars provides a command-line tool that precompiles .hbs files into JavaScript.

Installation

npm install handlebars@4.7.9 --save-dev

Precompiling a single file

npx handlebars src/templates/user.hbs -f dist/templates/user.js

-f specifies the output path. The command-line tool supports AMD, CommonJS, and global-variable output formats.

Precompiling a directory

npx handlebars src/templates -f dist/templates/all.js

This bundles all .hbs files under src/templates into one JavaScript file.


🛠 Using precompiled templates in a browser

Suppose you have precompiled user.hbs into dist/templates/user.js using the command line. To use it in a browser, follow these three steps:

  1. Load the runtime: Include the small handlebars.runtime.min.js file.
  2. Load the precompiled template: Include dist/templates/user.js.
  3. Render with data: Call Handlebars.templates.user(data) to get HTML.
index.html
<!-- 1. Load the small Handlebars runtime (rendering only) -->
<script src="node_modules/handlebars/dist/handlebars.runtime.min.js"></script>

<!-- 2. Load the precompiled template file -->
<script src="dist/templates/user.js"></script>

<!-- 3. Pass in data to get HTML -->
<script>
    var html = Handlebars.templates.user({ name: 'Ming', age: 18 });
    document.getElementById('app').innerHTML = html;
</script>
Handlebars.templates.user corresponds to the source filename user.hbs. For a file named card.hbs, call Handlebars.templates.card(data).
Load handlebars.runtime.min.js in the browser to get the size benefit of precompilation. The full handlebars.min.js build also includes the compiler, increasing the download size unnecessarily.

⚡ Precompiling in Node.js without the command line

If you prefer a Node.js script to a command-line invocation, use this approach:

build.js
const fs = require('fs');
const Handlebars = require('handlebars');

// 1. Read the template file
const source = fs.readFileSync('./src/templates/user.hbs', 'utf-8');

// 2. Precompile to generate the template specification source
const spec = Handlebars.precompile(source);

// 3. Save to a JavaScript file
fs.writeFileSync('./dist/templates/user.js', `module.exports = ${spec};`);

The generated spec cannot be called directly. First wrap it with Handlebars.template():

index.js
const Handlebars = require('handlebars/runtime');
const spec = require('./dist/templates/user.js');

// Wrap the precompiled specification in an executable template function
const template = Handlebars.template(spec);

// Pass in data to render
const html = template({ name: 'Ming', age: 18 });
console.log(html);
For beginners, the command-line tool is the simpler option. The Node.js script approach is useful when integrating precompilation into an automated workflow.

🧰 Integrating with build tools

In real projects, build tools often handle Handlebars precompilation:

  • Webpack: Use handlebars-loader.
  • Vite: Use vite-plugin-handlebars.
  • Rollup: Use rollup-plugin-handlebars.

These plugins handle .hbs templates as part of the build, allowing you to use them through your normal import or build workflow.

This course covers the core concepts and manual precompilation workflow. In a project, prefer a build tool plugin to automate this process.

❓ Questions and answers

Q1: Can I edit a precompiled template?

Edit the source .hbs file and precompile it again. The generated output contains compiled template code rather than the original editable template.

Q2: Do I need precompilation during development?

You can precompile or use the full build to compile templates as needed. Development prioritizes convenient debugging; precompilation is recommended for production.

Q3: Can a browser use precompiled templates with the full Handlebars build?

Yes, but the larger full build adds unnecessary download size and loading time.

Q4: How does Handlebars precompilation compare with Vue or React compilation?

Handlebars precompilation turns template strings into rendering functions. Vue and React compilation generates code for their respective runtimes. The idea is similar, but the generated output differs.


🧪 Exercise

Complete the following steps:

  1. Create src/templates/card.hbs with the following content:
src/templates/card.hbs
<div class="card">
    <h3>{{title}}</h3>
    <p>{{desc}}</p>
</div>
  1. Run the precompilation command:
# Enter the precompilation command here
  1. Write index.html to load and render the template in a browser using the runtime.

🎉 You have completed the Handlebars course! You now understand basic syntax, built-in helpers, template reuse, custom helpers, and precompilation, and can apply them in your projects.