Precompile handlebars templates into seperate JST (.js) files with Gulp

619 Views Asked by At

I have just recently moved from grunt to gulp and I am wanting to pre-compile my handlebars templates (with .handlebars extension) into separate .js files.

from:

  • www/templates/login.handlebars
  • www/templates/home.handlebars

to:

  • www/templates/login.js
  • www/templates/home.js

I am trying to use gulp but to no avail. A lot of the npm packages ask you to pass data to the compiler, but the data in my web app is collected mainly from ajax requests and then passed to the handlebars template.

My gulpfile.js:

// cache vars
var gulp = require('gulp'),
    rename = require('gulp-rename'),
    handlebars = require('gulp-compile-handlebars');

// start task
gulp.task('default', function(){

    return gulp.src( 'www/templates/*.handlebars' )
        .pipe( handlebars() )
        .pipe( rename('*.js') )
        .pipe( gulp.dest( 'www/templates' ) );
    });

});

The main reason i moved from Grunt to Gulp was because grunt doesnt seem to support the newer handlebars version (link here).

There are lots of examples how to compile handlebars templates but not in the way I want too (Is my way possible?)

Also i don't want to wrap my handlebar js files into a namespace if possible.

When i run my gulp task none of the .js files are generated any ideas?

1

There are 1 best solutions below

2
tiomno On

I have a not so clean solution that works for me. I'm using pump + gulp as it's a good idea to clean the source if something goes wrong while processing the pipe.

in the gulpfile.js:

const pump = require( 'pump' )
const handlebars = require( 'gulp-handlebars' )

gulp.task( 'default', ( done ) => {

    const templates = [
        'login',
        'home'
    ] // <-- You may want to get the list of files programmatically ;)

    let pipe = []

    templates.forEach( ( template ) => {
        pipe.push( gulp.src( 'www/templates/' + template + '.handlebars' ) )
        pipe.push( handlebars() )
        pipe.push( gulp.dest( 'www/templates/' ) )
    } )

    pump( pipe, done )

} )