Handlebars precompilation and runtime: Efficient production use
🎯 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:
| Build | Features | Use cases |
|---|---|---|
| Full build (handlebars) | Compiles and renders templates | Node.js backends and development |
| Runtime (handlebars/runtime) | Renders compiled templates; smaller size | Browsers 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:
- Load the full JavaScript build, which is larger.
- Pass a template string to
Handlebars.compile(). - 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:
- Use Node.js to compile templates into JavaScript during the build step.
- Load only the much smaller runtime in the browser.
- Call the compiled functions directly to render templates.
💡 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:
- Load the runtime: Include the small
handlebars.runtime.min.jsfile. - Load the precompiled template: Include
dist/templates/user.js. - Render with data: Call
Handlebars.templates.user(data)to get 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).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:
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():
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);
🧰 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.
❓ 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:
- Create
src/templates/card.hbswith the following content:
<div class="card">
<h3>{{title}}</h3>
<p>{{desc}}</p>
</div>
- Run the precompilation command:
# Enter the precompilation command here
- Write
index.htmlto 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.
