Programmatically Migrate a Website From Handlebars to Nunjucks

I’m currently migrating a large website from Handlebars to Nunjucks. Since the website is being updated daily, and because there are too many pages, I can’t convert the Handlebars syntax to Nunjucks syntax manually. To solve this, I started writing a script to convert the syntax programmatically using JavaScript (nodeJS). So far, it’s working very well. Here’s how I’m doing it, and how you can do something similar when confronted with a migration project.

Basically, the way it works is

  1. it recursively finds all files in a folder called “temp”
  2. if the file path ends with “hbs” – indicating it is a Handlebars file – then for each file, it executes a series of regex search and replace commands, e.g.
    • replace {{#if class}} with {% if class %}
    • replace {{/if}} with {% endif %}
    • and so on.

Those are simple search-and-replace situations. There may be a situation where you’ll need an advanced search and replace, e.g. when replacing

{{> social-list 
    dark="true" 
    centered="true"}} 

with

{% set dark="true" %}
{% set centered="true" %}
{% include social-list.njk %}

In this case, you can use a “replacer” function, which allows you to do much more to manipulate the output.

If you need to test regular expressions, https://regexr.com/ may come in handy.

When you’re all done and you’ve built the HTML files from both the handlebars templates and the nunjucks templates, you can write a script that recursively reads all HTML files in the build output folder and lists each HTML file path generated from each handlebars and nunjucks template along with their respective file size. The file sizes should be the same or almost the same. If some are not, then the migration script didn’t convert those templates correctly. Maybe something like:

File PathFile Size (KB) (hbs)File size (KB) (njk)Difference (KB)
/index.html181.3180.70.6
/about/index.html153.223.5129.7
/products/index.html353.6350.23.4