Skip to content

Handlebars Precompiler as Custom Handler #70

Description

@bryceschober

I'd like to implement a custom handler that both inlines and precompiles handlebars.js templates. I'm a novice when it comes to both node.js and promises. I want my handler to:

  1. Match any handlebars script tags of the text/x-handlebars-template type,
  2. Inline all HTML tags declared as inline,
  3. Pre-compile the handlebars template, and finally
  4. Emit the precompiled script contents.

My naive attempt looks like:

#!/usr/bin/env node

const { inlineSource } = require('inline-source');
const Handlebars = require('handlebars');

// Custom handler for pre-compiling handlebars.js
function process_handlebars_js( source, context ) {
    if( source.tag == 'script' && source.type == 'text/x-handlebars-template' ) {
        inlineSource(source.content, {
            compress: true,
            saveRemote: true,
        })
        .then(html => {
            source.content = Handlebars.precompile(html);
            return Promise.resolve();
        })
        .catch(err => {
            process.stderr.write(`Error in Handlebars.js processor: ${err}\n`);
            return Promise.reject();
        });
    }
    return Promise.resolve();
}

process.stdin.setEncoding('utf8');

source = '';
process.stdin.on('readable', () => {
    let chunk = process.stdin.read();
    if (chunk!==null) source += chunk;
});

process.stdin.on('end', () => {
    inlineSource(source, {
        compress: true,
        saveRemote: true,
        handlers: [ process_handlebars_js ]
    })
    .then(html => {
        process.stdout.write(html + '\n');
        process.exit(0);
    })
    .catch(err => {
        process.stderr.write(`Error: ${err}\n`);
        return process.exit(1);
    });
});

But this yields the error:

Error in Handlebars.js processor: TypeError: Cannot read property 'replace' of null

Any pointers on the right direction?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions